Class: Seam::Paginator

Inherits:
Object
  • Object
show all
Defined in:
lib/seam/paginator.rb

Instance Method Summary collapse

Constructor Details

#initialize(request, params = {}) ⇒ Paginator

Returns a new instance of Paginator.

Raises:

  • (ArgumentError)


11
12
13
14
15
16
17
# 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)

  @request = request
  @params = params.transform_keys(&:to_sym)
end

Instance Method Details

#first_pageObject



19
20
21
# File 'lib/seam/paginator.rb', line 19

def first_page
  fetch_page(@params)
end

#flattenObject



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/seam/paginator.rb', line 46

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_listObject



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/seam/paginator.rb', line 32

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



23
24
25
26
27
28
29
30
# File 'lib/seam/paginator.rb', line 23

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