Class: Jikanrb::Pagination::Paginator

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

Overview

Paginator class for iterating through all pages

Instance Method Summary collapse

Constructor Details

#initialize(client, method, **params) ⇒ Paginator

Returns a new instance of Paginator.

Parameters:

  • client (Jikanrb::Client)

    Client instance

  • method (Symbol)

    Method name to call (e.g., :top_anime)

  • params (Hash)

    Additional parameters for the method



88
89
90
91
92
93
# File 'lib/jikanrb/pagination.rb', line 88

def initialize(client, method, **params)
  @client = client
  @method = method
  @params = params
  @current_page = params[:page] || 1
end

Instance Method Details

#allArray<Hash>

Get all items from all pages as an array

Returns:

  • (Array<Hash>)

    All items



113
114
115
# File 'lib/jikanrb/pagination.rb', line 113

def all
  to_a
end

#each {|Hash| ... } ⇒ Object

Iterate through all items across all pages

Yields:

  • (Hash)

    Each item from the API response



97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/jikanrb/pagination.rb', line 97

def each(&block)
  loop do
    response = @client.public_send(@method, **@params, page: @current_page)
    data = response['data'] || []

    data.each(&block)

    pagination = PaginationInfo.new(response)
    break unless pagination.has_next_page?

    @current_page = pagination.next_page
  end
end

#take_pages(page_count) ⇒ Array<Hash>

Get items from the first N pages

Parameters:

  • page_count (Integer)

    Number of pages to fetch

Returns:

  • (Array<Hash>)

    Items from the specified number of pages



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/jikanrb/pagination.rb', line 120

def take_pages(page_count)
  items = []
  page_count.times do
    response = @client.public_send(@method, **@params, page: @current_page)
    data = response['data'] || []

    items.concat(data)

    pagination = PaginationInfo.new(response)
    break unless pagination.has_next_page?

    @current_page = pagination.next_page
  end
  items
end