Class: Mercadopago::Pagination::Iterator

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

Overview

Lazy Enumerator that auto-fetches all pages from a MercadoPago search endpoint.

Examples:

sdk.payment.search_auto_paging_iter(status: 'approved').each do |payment|
  process(payment)
end

Constant Summary collapse

DEFAULT_PAGE_SIZE =
100

Instance Method Summary collapse

Constructor Details

#initialize(search_fn, filters: nil, request_options: nil, limit: DEFAULT_PAGE_SIZE) ⇒ Iterator

Returns a new instance of Iterator.

Parameters:

  • search_fn (Proc)

    callable that accepts filters and request_options and returns a response hash with :status and :response keys

  • filters (Hash, nil) (defaults to: nil)

    initial search filters; :limit and :offset are managed

  • request_options (Object, nil) (defaults to: nil)

    per-call overrides forwarded to search_fn

  • limit (Integer) (defaults to: DEFAULT_PAGE_SIZE)

    items per page



21
22
23
24
25
26
# File 'lib/mercadopago/pagination/iterator.rb', line 21

def initialize(search_fn, filters: nil, request_options: nil, limit: DEFAULT_PAGE_SIZE)
  @search_fn       = search_fn
  @filters         = (filters || {}).dup
  @request_options = request_options
  @limit           = limit.to_i.positive? ? limit.to_i : DEFAULT_PAGE_SIZE
end

Instance Method Details

#eachObject

Lazily yields each result item across all pages. Compatible with Enumerable (+map+, select, first, etc.).



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

def each
  return enum_for(:each) unless block_given?

  offset = (@filters[:offset] || @filters['offset'] || 0).to_i

  loop do
    page_filters = @filters.merge(limit: @limit, offset: offset)
    result       = @search_fn.call(filters: page_filters, request_options: @request_options)
    body         = extract_body(result)
    items        = extract_items(body)
    total        = extract_total(body)

    break if items.empty?

    items.each { |item| yield item }

    offset += items.size
    break if total.positive? && offset >= total
  end
end