Skip to content
Browse files

Added an enumerator over all results.

  • Loading branch information...
1 parent 86e1bc6 commit ee212a12c5b7777f0ac61e8a8d0029f07fff4d07 @dblock committed Mar 26, 2012
Showing with 40 additions and 1 deletion.
  1. +4 −0 CHANGELOG.md
  2. +7 −0 README.md
  3. +15 −0 lib/garb/model.rb
  4. +14 −1 test/unit/garb/model_test.rb
View
4 CHANGELOG.md
@@ -1,3 +1,7 @@
+Version 0.9.x
+
+ * Added Garb::Model.all that paginates all data
+
Version 0.9.2
* Removed all deprecated features: Garb::Report, Garb::Resource, Garb::Profile, and Garb::Account
View
7 README.md
@@ -74,6 +74,13 @@ Get the Results
Be forewarned, these numbers are for the last **30** days and may be slightly different from the numbers displayed in Google Analytics' dashboard for **1 month**.
+Get all Results
+---------------
+
+Google Analytics returns 1000 results at a time. To paginate over all results:
+
+ > Exits.all(profile) { |exit| ... }
+
Other Parameters
----------------
View
15 lib/garb/model.rb
@@ -43,6 +43,21 @@ def results(profile, options = {})
data = send_request_for_data(profile, build_params(param_set))
ReportResponse.new(data, instance_klass).results
end
+
+ def all(profile, options = {}, &block)
+ limit = options.delete(:limit)
+ total = 0
+ options = {}
+ options[:limit] = limit if limit
+ while ((rs = results(profile, options)) && rs.any?)
+ rs.each do |r|
+ total += 1
+ yield r
+ end
+ options[:offset] = total
+ end
+ self
+ end
private
def send_request_for_data(profile, params)
View
15 test/unit/garb/model_test.rb
@@ -108,7 +108,7 @@ class ModelTest < MiniTest::Unit::TestCase
assert_equal ['result'], @test_model.results(@profile, :limit => 20)
assert_data_params(@params.merge({'max-results' => 20}))
end
-
+
should "be able to offset" do
assert_equal ['result'], @test_model.results(@profile, :offset => 10)
assert_data_params(@params.merge({'start-index' => 10}))
@@ -128,6 +128,19 @@ class ModelTest < MiniTest::Unit::TestCase
assert_equal ['result'], @test_model.results(@profile)
assert_received(ReportResponse, :new) {|e| e.with("raw report data", ResultKlass)}
end
+
+ should "be able to fetch multiple pages of results" do
+ results = []
+ count = 0
+ @test_model.all(@profile) do |result|
+ results << result
+ # stub a subsequent response
+ count += 1
+ ReportResponse.stubs(:new).returns(stub(:results => [])) if count == 2
+ end
+ assert_equal ['result', 'result'], results
+ end
+
end
# should "return results as an array of the class it belongs to, if that class is an ActiveRecord descendant"

0 comments on commit ee212a1

Please sign in to comment.
Something went wrong with that request. Please try again.