Class: Anypost::Page

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/anypost/page.rb

Overview

One page of a list result.

Mirrors the wire envelope (‘data`, `has_more`, `next_cursor`) and is enumerable: iterating walks every remaining page automatically, re-fetching with `after = next_cursor`.

page = client.domains.list           # one page
page.data                            # just this page's items

client.domains.list.each do |domain| # every domain, across all pages
  puts domain.name
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response) {|cursor| ... } ⇒ Page

Returns a new instance of Page.

Parameters:

  • response (Hash)

    the decoded page envelope

Yield Parameters:



28
29
30
31
32
33
34
35
# File 'lib/anypost/page.rb', line 28

def initialize(response, &fetch_next)
  raw = response.is_a?(Hash) ? response : {}
  @data = (raw["data"] || []).map { |item| Response.wrap(item) }
  @has_more = raw["has_more"] || false
  cursor = raw["next_cursor"]
  @next_cursor = cursor.is_a?(String) ? cursor : nil
  @fetch_next = fetch_next
end

Instance Attribute Details

#dataArray<Response> (readonly)

Returns the items on this page.

Returns:

  • (Array<Response>)

    the items on this page



20
21
22
# File 'lib/anypost/page.rb', line 20

def data
  @data
end

#has_moreBoolean (readonly)

Returns:

  • (Boolean)


22
23
24
# File 'lib/anypost/page.rb', line 22

def has_more
  @has_more
end

#next_cursorString? (readonly)

Returns:

  • (String, nil)


24
25
26
# File 'lib/anypost/page.rb', line 24

def next_cursor
  @next_cursor
end

Instance Method Details

#eachObject



45
46
47
48
49
50
51
52
53
# File 'lib/anypost/page.rb', line 45

def each
  return enum_for(:each) unless block_given?

  page = self
  while page
    page.data.each { |item| yield item }
    page = page.next_page
  end
end

#next_pagePage?

Fetch the next page, or nil when there are no more.

Returns:



39
40
41
42
43
# File 'lib/anypost/page.rb', line 39

def next_page
  return nil unless @has_more && @next_cursor

  @fetch_next.call(@next_cursor)
end