Class: FinchAPI::Page

Inherits:
Object
  • Object
show all
Includes:
Type::BasePage
Defined in:
lib/finch-api/page.rb

Overview

Examples:

if page.has_next?
  page = page.next_page
end
page.auto_paging_each do |item|
  puts(item)
end
items =
  page
  .to_enum
  .lazy
  .select { _1.object_id.even? }
  .map(&:itself)
  .take(2)
  .to_a

items => Array

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Type::BasePage

#to_enum

Constructor Details

#initialize(client:, req:, headers:, page_data:) ⇒ Page

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of Page.

Parameters:



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/finch-api/page.rb', line 40

def initialize(client:, req:, headers:, page_data:)
  super
  model = req.fetch(:model)

  case page_data
  in {data: Array | nil => data}
    @data = data&.map { FinchAPI::Type::Converter.coerce(model, _1) }
  else
  end

  case page_data
  in {paging: Hash | nil => paging}
    @paging = FinchAPI::Type::Converter.coerce(FinchAPI::Models::Paging, paging)
  else
  end
end

Instance Attribute Details

#dataArray<Object>?

Returns:

  • (Array<Object>, nil)


29
30
31
# File 'lib/finch-api/page.rb', line 29

def data
  @data
end

#pagingFinchAPI::Models::Paging



32
33
34
# File 'lib/finch-api/page.rb', line 32

def paging
  @paging
end

Instance Method Details

#auto_paging_each(&blk) ⇒ Object

Parameters:

  • blk (Proc)


75
76
77
78
79
80
81
82
83
84
85
# File 'lib/finch-api/page.rb', line 75

def auto_paging_each(&blk)
  unless block_given?
    raise ArgumentError.new("A block must be given to ##{__method__}")
  end
  page = self
  loop do
    page.data&.each { blk.call(_1) }
    break unless page.next_page?
    page = page.next_page
  end
end

#inspectString

Returns:

  • (String)


88
89
90
# File 'lib/finch-api/page.rb', line 88

def inspect
  "#<#{self.class}:0x#{object_id.to_s(16)} data=#{data.inspect} paging=#{paging.inspect}>"
end

#next_pageFinchAPI::Page

Returns:

Raises:

  • (FinchAPI::HTTP::Error)


64
65
66
67
68
69
70
71
72
# File 'lib/finch-api/page.rb', line 64

def next_page
  unless next_page?
    message = "No more pages available. Please check #next_page? before calling ##{__method__}"
    raise RuntimeError.new(message)
  end

  req = FinchAPI::Util.deep_merge(@req, {query: {offset: paging&.offset.to_i + data.to_a.size}})
  @client.request(req)
end

#next_page?Boolean

Returns:

  • (Boolean)


58
59
60
# File 'lib/finch-api/page.rb', line 58

def next_page?
  paging&.offset.to_i + data.to_a.size < paging&.count.to_i
end