Class: Pago::Paginator

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/pago/paginator.rb

Overview

Lazily walks every page of a paginated endpoint.

It is a plain Enumerable over the items, so the whole standard library applies: each, map, select, first(20), lazy, each_slice… Pages are fetched on demand, one request at a time, and #pages exposes the raw page objects when the pagination metadata itself is needed.

Examples:

client.products.list_each(organization_id: id).first(50)

Instance Method Summary collapse

Constructor Details

#initialize {|page| ... } ⇒ Paginator

Returns a new instance of Paginator.

Yield Parameters:

  • page (Integer)

    the 1-based page number to fetch.

Yield Returns:

  • (Object)

    the deserialized page, answering items and pagination.

Raises:

  • (ArgumentError)


18
19
20
21
22
# File 'lib/pago/paginator.rb', line 18

def initialize(&fetch_page)
  raise ArgumentError, "Pago::Paginator requires a block" unless block_given?

  @fetch_page = fetch_page
end

Instance Method Details

#each {|item| ... } ⇒ Enumerator

Returns when no block is given.

Yield Parameters:

  • item (Object)

    every item of every page.

Returns:

  • (Enumerator)

    when no block is given.



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/pago/paginator.rb', line 26

def each
  return to_enum(:each) unless block_given?

  pages.each do |page|
    items = page.respond_to?(:items) ? page.items : nil
    break if items.nil?

    items.each { |item| yield(item) }
  end
  self
end

#pagesEnumerator

Returns the successive page objects, metadata included.

Returns:

  • (Enumerator)

    the successive page objects, metadata included.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/pago/paginator.rb', line 39

def pages
  return to_enum(:pages) unless block_given?

  number = 1
  loop do
    page = @fetch_page.call(number)
    break if page.nil?

    yield(page)
    max_page = max_page_of(page)
    break if max_page.nil? || number >= max_page

    number += 1
  end
  self
end