Class: Pinnacle::Internal::CursorPageIterator

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/pinnacle/internal/iterators/cursor_page_iterator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(initial_cursor:, cursor_field:, &block) ⇒ Pinnacle::Internal::CursorPageIterator

Instantiates a CursorPageIterator, an Enumerable class which wraps calls to a cursor-based paginated API and yields pages of items.

Parameters:

  • initial_cursor (String)

    The initial cursor to use when iterating, if any.

  • cursor_field (Symbol)

    The name of the field in API responses to extract the next cursor from.

  • block (Proc)

    A block which is responsible for receiving a cursor to use and returning the given page from the API. The block should return a two-element array: [parsed_page, raw_http_response].



19
20
21
22
23
24
25
# File 'lib/pinnacle/internal/iterators/cursor_page_iterator.rb', line 19

def initialize(initial_cursor:, cursor_field:, &block)
  @need_initial_load = initial_cursor.nil?
  @cursor = initial_cursor
  @cursor_field = cursor_field
  @get_next_page = block
  @http_response = nil
end

Instance Attribute Details

#http_responseNet::HTTPResponse? (readonly)

The raw HTTP response from the most recent page response.

Returns:

  • (Net::HTTPResponse, nil)


10
11
12
# File 'lib/pinnacle/internal/iterators/cursor_page_iterator.rb', line 10

def http_response
  @http_response
end

Instance Method Details

#each(&block) ⇒ NilClass

Iterates over each page returned by the API.

Parameters:

  • block (Proc)

    The block which each retrieved page is yielded to.

Returns:

  • (NilClass)


31
32
33
34
35
# File 'lib/pinnacle/internal/iterators/cursor_page_iterator.rb', line 31

def each(&block)
  while (page = next_page)
    block.call(page)
  end
end

#next?Boolean

Whether another page will be available from the API.

Returns:

  • (Boolean)


40
41
42
# File 'lib/pinnacle/internal/iterators/cursor_page_iterator.rb', line 40

def next?
  @need_initial_load || !@cursor.nil?
end

#next_pageObject?

Retrieves the next page from the API.

Returns:

  • (Object, nil)


47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/pinnacle/internal/iterators/cursor_page_iterator.rb', line 47

def next_page
  return if !@need_initial_load && @cursor.nil?

  @need_initial_load = false
  result = @get_next_page.call(@cursor)
  if result.is_a?(Array)
    fetched_page, raw_response = result
    @http_response = raw_response
  else
    fetched_page = result
  end
  @cursor = fetched_page.send(@cursor_field)
  fetched_page
end