Module: Pluggy::Lists

Defined in:
lib/pluggy/lists.rb,
lib/pluggy/lists/base_list.rb,
lib/pluggy/lists/array_list.rb,
lib/pluggy/lists/cursor_list.rb,
lib/pluggy/lists/offset_list.rb

Defined Under Namespace

Classes: ArrayList, BaseList, CursorList, OffsetList

Class Method Summary collapse

Class Method Details

.wrap(payload, klass:, requestor:, path:, filters: {}, client: nil, paginated: false) ⇒ Object

Pick a list type by looking at the payload rather than by trusting the endpoint's declared schema.

This is deliberate: GET /categories declares a bare array but its own example is an offset envelope, so any per-endpoint assumption is a coin flip against the live API. Sniffing costs one hash lookup and makes every list endpoint present the same interface.



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

def self.wrap(payload, klass:, requestor:, path:, filters: {}, client: nil, paginated: false)
  common = { klass: klass, requestor: requestor, path: path, filters: filters, client: client }

  case payload
  when Array
    ArrayList.new(payload, **common)
  when Hash
    if payload.key?("next")
      CursorList.new(payload, **common)
    elsif payload.key?("results")
      OffsetList.new(payload, paginated: paginated, **common)
    else
      raise Error, "unrecognized list envelope from #{path} (keys: #{payload.keys.inspect})"
    end
  else
    raise Error, "expected an array or object from #{path}, got #{payload.class}"
  end
end