Class: Seam::Paginator
- Inherits:
-
Object
- Object
- Seam::Paginator
- Defined in:
- lib/seam/paginator.rb
Instance Method Summary collapse
- #first_page ⇒ Object
- #flatten ⇒ Object
- #flatten_to_list ⇒ Object
-
#initialize(request, params = {}) ⇒ Paginator
constructor
A new instance of Paginator.
- #next_page(next_page_cursor) ⇒ Object
Constructor Details
#initialize(request, params = {}) ⇒ Paginator
Returns a new instance of Paginator.
11 12 13 14 15 16 17 18 19 20 |
# File 'lib/seam/paginator.rb', line 11 def initialize(request, params = {}) raise ArgumentError, "request must be a Method" unless request.is_a?(Method) raise ArgumentError, "params must be a Hash" unless params.is_a?(Hash) unless request.parameters.any? { |_, name| name == :page_cursor } raise ArgumentError, "request does not support pagination" end @request = request @params = params.transform_keys(&:to_sym) end |
Instance Method Details
#first_page ⇒ Object
22 23 24 |
# File 'lib/seam/paginator.rb', line 22 def first_page fetch_page(@params) end |
#flatten ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/seam/paginator.rb', line 49 def flatten Enumerator.new do |yielder| current_items, pagination = first_page current_items&.each { |item| yielder << item } while pagination&.has_next_page? && (cursor = pagination.next_page_cursor) current_items, pagination = next_page(cursor) current_items&.each { |item| yielder << item } end end end |
#flatten_to_list ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/seam/paginator.rb', line 35 def flatten_to_list all_items = [] current_items, pagination = first_page all_items.concat(current_items) if current_items while pagination&.has_next_page? && (cursor = pagination.next_page_cursor) current_items, pagination = next_page(cursor) all_items.concat(current_items) if current_items end all_items end |
#next_page(next_page_cursor) ⇒ Object
26 27 28 29 30 31 32 33 |
# File 'lib/seam/paginator.rb', line 26 def next_page(next_page_cursor) if next_page_cursor.nil? || next_page_cursor.empty? raise ArgumentError, "Cannot get the next page with a nil or empty next_page_cursor." end fetch_page(@params.merge(page_cursor: next_page_cursor)) end |