Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion lib/garb/model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ module Garb
module Model
MONTH = (60 * 60 * 24 * 30).freeze
URL = 'https://www.googleapis.com/analytics/v3/data/ga'.freeze
MAX_RESULTS = 10_000 # maximum allowed per request

def self.extended(base)
ProfileReports.add_report_method(base)
Expand Down Expand Up @@ -54,7 +55,7 @@ def all_results(profile, options = {})
raise ArgumentError, ':offset must be greater than or equal to 1' if offset < 1
options[:offset] = offset if options[:offset]

options[:limit] = 10_000 # maximum allowed
options[:limit] = page_size(limit, 0)
results = nil
while ((rs = results(profile, options)) && !rs.empty?)
results = results ? results + rs : rs
Expand All @@ -63,13 +64,19 @@ def all_results(profile, options = {})

break if limit && results.size >= limit
break if next_offset > results.total_results

options[:limit] = page_size(limit, results.size)
end
results ||= rs # empty result set when nothing was fetched
limit ? results[0...limit] : results
end

private

def page_size(limit, fetched)
limit ? [limit - fetched, MAX_RESULTS].min : MAX_RESULTS
end

def send_request_for_data(profile, params)
request = Request::Data.new(profile.session, URL, params)
response = request.send_request
Expand Down
3 changes: 3 additions & 0 deletions test/unit/garb/model_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,10 @@ class ModelTest < MiniTest::Unit::TestCase
ReportResponse.stubs(:new).returns(*pages)

@start_indexes = []
@max_results = []
Request::Data.stubs(:new).with do |_session, _url, params|
@start_indexes << params['start-index']
@max_results << params['max-results']
true
end.returns(stub(send_request: @response))
end
Expand All @@ -212,6 +214,7 @@ class ModelTest < MiniTest::Unit::TestCase
results = @test_model.results(@profile, all: true, offset: 11, limit: 12)
assert_equal @rows[0...12], results.to_a
assert_equal [11, 21], @start_indexes
assert_equal [12, 2], @max_results
end
end

Expand Down