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 Attribute Summary collapse

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



19
20
21
22
23
24
# File 'lib/discordrb/paginator.rb', line 19

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

Instance Attribute Details

#amount_fetchedInteger (readonly)

Returns the total amount of elements that have been fetched so far.

Returns:

  • (Integer)

    the total amount of elements that have been fetched so far.



11
12
13
# File 'lib/discordrb/paginator.rb', line 11

def amount_fetched
  @amount_fetched
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.



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

def each
  last_page = nil
  until limit_exceeded?
    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
      @amount_fetched += 1
      break if limit_exceeded?
    end

    last_page = page
  end
end