Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added methods for fetching all contacts in one call (rendering in one…

… or more API calls)
  • Loading branch information...
commit 687ce25d5039a20167cc816e408e4f2976c61342 1 parent c55f2fa
@pietern pietern authored
Showing with 47 additions and 0 deletions.
  1. +18 −0 lib/contacts/google.rb
  2. +29 −0 spec/gmail/fetching_spec.rb
View
18 lib/contacts/google.rb
@@ -153,8 +153,26 @@ def contacts(options = {})
response = get(params)
parse_contacts response_body(response)
end
+
+ # Fetches contacts using multiple API calls when necessary
+ def all_contacts(options = {}, chunk_size = 200)
+ in_chunks(options, :contacts, chunk_size)
+ end
protected
+
+ def in_chunks(options, what, chunk_size)
+ returns = []
+ offset = 0
+
+ begin
+ chunk = send(what, options.merge(:offset => offset, :limit => chunk_size))
+ returns.push(*chunk)
+ offset += chunk_size
+ end while chunk.size == chunk_size
+
+ returns
+ end
def response_body(response)
unless response['Content-Encoding'] == 'gzip'
View
29 spec/gmail/fetching_spec.rb
@@ -157,6 +157,35 @@ def expect_params(params, partial = false)
end
end
+
+ describe 'Retrieving all contacts (in chunks)' do
+
+ before :each do
+ @gmail = create
+ end
+
+ it 'should make only one API call when no more is needed' do
+ @gmail.expects(:contacts).with(instance_of(Hash)).once.returns((0..8).to_a)
+
+ @gmail.all_contacts({}, 10).should == (0..8).to_a
+ end
+
+ it 'should make multiple calls to :contacts when needed' do
+ @gmail.expects(:contacts).with(has_entries(:offset => 0 , :limit => 10)).returns(( 0..9 ).to_a)
+ @gmail.expects(:contacts).with(has_entries(:offset => 10, :limit => 10)).returns((10..19).to_a)
+ @gmail.expects(:contacts).with(has_entries(:offset => 20, :limit => 10)).returns((20..24).to_a)
+
+ @gmail.all_contacts({}, 10).should == (0..24).to_a
+ end
+
+ it 'should make one extra API call when not sure whether there are more contacts' do
+ @gmail.expects(:contacts).with(has_entries(:offset => 0 , :limit => 10)).returns((0..9).to_a)
+ @gmail.expects(:contacts).with(has_entries(:offset => 10, :limit => 10)).returns([])
+
+ @gmail.all_contacts({}, 10).should == (0..9).to_a
+ end
+
+ end
def create
Contacts::Google.new('dummytoken')
Please sign in to comment.
Something went wrong with that request. Please try again.