Skip to content

Commit

Permalink
googleapis#459 - Fix iteration for genomics API which only has 1 item…
Browse files Browse the repository at this point in the history
… per page
  • Loading branch information
sqrrrl committed Aug 31, 2016
1 parent 8735e62 commit 70596d2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
15 changes: 10 additions & 5 deletions lib/google/apis/core/base_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,16 @@ def each
loop do
@last_result = @fetch_proc.call(page_token)
items = @last_result.send(@items_field)
for item in items
item_count = item_count + 1
break if @max && item_count > @max
yield item
end unless items.nil?
if items.kind_of?(Array)
for item in items
item_count = item_count + 1
break if @max && item_count > @max
yield item
end
elsif items
# yield singular non-nil items (for genomics API)
yield items
end
break if @max && item_count >= @max
break if @last_result.next_page_token.nil? || @last_result.next_page_token == page_token
page_token = @last_result.next_page_token
Expand Down
10 changes: 7 additions & 3 deletions spec/google/apis/core/service_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -248,9 +248,9 @@
context 'with fetch_all' do
let(:responses) do
data = {}
data[nil] = OpenStruct.new(next_page_token: 'p1', items: ['a', 'b', 'c'], alt_items: [1, 2 , 3])
data['p1'] = OpenStruct.new(next_page_token: 'p2', items: ['d', 'e', 'f'], alt_items: [4, 5, 6])
data['p2'] = OpenStruct.new(next_page_token: nil, items: ['g', 'h', 'i'], alt_items: [7,8, 9])
data[nil] = OpenStruct.new(next_page_token: 'p1', items: ['a', 'b', 'c'], alt_items: [1, 2 , 3], singular: 'foo')
data['p1'] = OpenStruct.new(next_page_token: 'p2', items: ['d', 'e', 'f'], alt_items: [4, 5, 6], singular: 'bar')
data['p2'] = OpenStruct.new(next_page_token: nil, items: ['g', 'h', 'i'], alt_items: [7,8, 9], singular: 'baz')
data
end

Expand All @@ -274,6 +274,10 @@
expect(service.fetch_all(items: :alt_items) { |token| responses[token] } ).to contain_exactly(1, 2, 3, 4, 5, 6, 7, 8, 9)
end

it 'should allow iterating over singular items' do
expect(service.fetch_all(items: :singular) { |token| responses[token] } ).to contain_exactly('foo', 'bar', 'baz')
end

it 'should allow limiting the number of items to fetch' do
expect(service.fetch_all(max: 5) { |token| responses[token] } ).to contain_exactly('a', 'b', 'c', 'd', 'e')
end
Expand Down

0 comments on commit 70596d2

Please sign in to comment.