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

Returns a new instance of PagedResults.

Parameters:

  • service (BaseService)

    Current service instance

  • max (Fixnum) (defaults to: nil)

    Maximum number of items to iterate over. Nil if no limit

  • cache (Boolean) (defaults to: true)

    True (default) if results should be cached so multiple iterations can be used.

  • items (Symbol) (defaults to: :items)

    Name of the field in the result containing the items. Defaults to :items



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

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.



36
37
38
# File 'lib/google/apis/core/base_service.rb', line 36

def last_result
  @last_result
end

Instance Method Details

#eachObject

Iterates over result set, fetching additional pages as needed



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
88
89
90
# File 'lib/google/apis/core/base_service.rb', line 63

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.to_s.empty? || next_page_token == page_token
    page_token = next_page_token
  end
end