Class: Pago::Paginator
- Inherits:
-
Object
- Object
- Pago::Paginator
- 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.
Instance Method Summary collapse
-
#each {|item| ... } ⇒ Enumerator
When no block is given.
-
#initialize {|page| ... } ⇒ Paginator
constructor
A new instance of Paginator.
-
#pages ⇒ Enumerator
The successive page objects, metadata included.
Constructor Details
#initialize {|page| ... } ⇒ Paginator
Returns a new instance of Paginator.
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.
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 |
#pages ⇒ Enumerator
Returns 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 |