Class: Polar::PaginatedResponse

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/polar/pagination.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client, path, params = {}, headers = {}) ⇒ PaginatedResponse

Returns a new instance of PaginatedResponse.



9
10
11
12
13
14
15
16
17
# File 'lib/polar/pagination.rb', line 9

def initialize(client, path, params = {}, headers = {})
  @client = client
  @path = path
  @params = params.dup
  @headers = headers
  @current_page = nil
  @total_count = nil
  @items_cache = {}
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



7
8
9
# File 'lib/polar/pagination.rb', line 7

def client
  @client
end

#current_pageObject (readonly)

Returns the value of attribute current_page.



7
8
9
# File 'lib/polar/pagination.rb', line 7

def current_page
  @current_page
end

#headersObject (readonly)

Returns the value of attribute headers.



7
8
9
# File 'lib/polar/pagination.rb', line 7

def headers
  @headers
end

#paramsObject (readonly)

Returns the value of attribute params.



7
8
9
# File 'lib/polar/pagination.rb', line 7

def params
  @params
end

#pathObject (readonly)

Returns the value of attribute path.



7
8
9
# File 'lib/polar/pagination.rb', line 7

def path
  @path
end

#total_countObject (readonly)

Returns the value of attribute total_count.



7
8
9
# File 'lib/polar/pagination.rb', line 7

def total_count
  @total_count
end

Instance Method Details

#auto_paginateObject



38
39
40
41
42
# File 'lib/polar/pagination.rb', line 38

def auto_paginate
  all_items = []
  each { |item| all_items << item }
  all_items
end

#countObject



52
53
54
# File 'lib/polar/pagination.rb', line 52

def count
  first_page['pagination']['total'] if first_page.dig('pagination')
end

#each(&block) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/polar/pagination.rb', line 19

def each(&block)
  return enum_for(:each) unless block_given?

  page = 1
  loop do
    response_data = fetch_page(page)
    items = extract_items(response_data)

    break if items.empty?

    items.each(&block)

    # Check if there are more pages
    break unless has_next_page?(response_data, page)

    page += 1
  end
end

#first_pageObject



44
45
46
# File 'lib/polar/pagination.rb', line 44

def first_page
  @first_page ||= fetch_page(1)
end

#page(page_number) ⇒ Object



48
49
50
# File 'lib/polar/pagination.rb', line 48

def page(page_number)
  fetch_page(page_number)
end

#total_pagesObject



56
57
58
59
60
61
62
63
# File 'lib/polar/pagination.rb', line 56

def total_pages
  pagination_info = first_page.dig('pagination')
  return nil unless pagination_info

  total = pagination_info['total']
  per_page = pagination_info['per_page'] || pagination_info['limit'] || 20
  (total.to_f / per_page).ceil
end