Class: DuffelAPI::Paginator

Inherits:
Object
  • Object
show all
Defined in:
lib/duffel_api/paginator.rb

Overview

An internal class used within the library to paginated automatically thruogh results from list actions that can be spread over multiple pages

Instance Method Summary collapse

Constructor Details

#initialize(service:, options:) ⇒ Paginator

Returns a new instance of Paginator.

Parameters:

  • service (Services::BaseService)

    a service which implements ‘#list`

  • options (Hash)

    the options originally passed to ‘#all`



9
10
11
12
# File 'lib/duffel_api/paginator.rb', line 9

def initialize(service:, options:)
  @service = service
  @options = options
end

Instance Method Details

#enumeratorEnumerator

Returns an enumerator that is able to automatically cycle through paginated data returned by the API

Returns:

  • (Enumerator)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/duffel_api/paginator.rb', line 18

def enumerator
  response = @service.list(@options)

  Enumerator.new do |yielder|
    loop do
      response.records.each { |item| yielder << item }

      after_cursor = response.after
      break if after_cursor.nil?

      @options[:params] ||= {}
      @options[:params] = @options[:params].merge(after: after_cursor)
      response = @service.list(@options)
    end
  end.lazy
end