Class: Discordrb::Paginator

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/discordrb/paginator.rb

Overview

Utility class for wrapping paginated endpoints. It is Enumerable, similar to an Array, so most of the same methods can be used to filter the results of the request that it wraps. If you simply want an array of all of the results, #to_a can be called.

Instance Method Summary collapse

Constructor Details

#initialize(limit, direction) {|Array, nil| ... } ⇒ Paginator

Creates a new Discordrb::Paginator

Parameters:

  • limit (Integer)

    the maximum number of items to request before stopping

  • direction (:up, :down)

    the order in which results are returned in

Yields:

  • (Array, nil)

    the last page of results, or nil if this is the first iteration. This should be used to request the next page of results.

Yield Returns:

  • (Array)

    the next page of results



16
17
18
19
20
21
# File 'lib/discordrb/paginator.rb', line 16

def initialize(limit, direction, &block)
  @count = 0
  @limit = limit
  @direction = direction
  @block = block
end

Instance Method Details

#eachObject

Yields every item produced by the wrapped request, until it returns no more results or the configured limit is reached.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/discordrb/paginator.rb', line 25

def each
  last_page = nil
  until limit_check
    page = @block.call(last_page)
    return if page.empty?

    enumerator = case @direction
                 when :down
                   page.each
                 when :up
                   page.reverse_each
                 end

    enumerator.each do |item|
      yield item
      @count += 1
      break if limit_check
    end

    last_page = page
  end
end