Class: Google::Apis::Core::PagedResults

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/google/apis/core/base_service.rb

Overview

Helper class for enumerating over a result set requiring multiple fetches

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(service, max: nil, items: :items, cache: true, response_page_token: :next_page_token, &block) ⇒ PagedResults


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/google/apis/core/base_service.rb', line 43

def initialize(service, max: nil, items: :items, cache: true, response_page_token: :next_page_token, &block)
  @service = service
  @block = block
  @max = max
  @items_field = items
  @response_page_token_field = response_page_token
  if cache
    @result_cache = Hash.new do |h, k|
      h[k] = @block.call(k, @service)
    end
    @fetch_proc = Proc.new { |token| @result_cache[token] }
  else
    @fetch_proc = Proc.new { |token| @block.call(token, @service) }
  end
end

Instance Attribute Details

#last_resultObject (readonly)

Returns the value of attribute last_result


33
34
35
# File 'lib/google/apis/core/base_service.rb', line 33

def last_result
  @last_result
end

Instance Method Details

#eachObject

Iterates over result set, fetching additional pages as needed


60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/google/apis/core/base_service.rb', line 60

def each
  page_token = nil
  item_count = 0
  loop do
    @last_result = @fetch_proc.call(page_token)
    items = @last_result.send(@items_field)
    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.kind_of?(Hash)
      items.each do |key, val|
        item_count = item_count + 1
        break if @max && item_count > @max
        yield key, val
      end
    elsif items
      # yield singular non-nil items (for genomics API)
      yield items
    end
    break if @max && item_count >= @max
    next_page_token = @last_result.send(@response_page_token_field)
    break if next_page_token.nil? || next_page_token == page_token
    page_token = next_page_token
  end
end