Class: Retab::Types::ListStruct

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/retab/types/list_struct.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data: [], list_metadata: {}, last_response: nil, fetch_next: nil) ⇒ ListStruct

Returns a new instance of ListStruct.



17
18
19
20
21
22
# File 'lib/retab/types/list_struct.rb', line 17

def initialize(data: [], list_metadata: {}, last_response: nil, fetch_next: nil)
  @data = data
  @list_metadata = 
  @last_response = last_response
  @fetch_next = fetch_next
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



15
16
17
# File 'lib/retab/types/list_struct.rb', line 15

def data
  @data
end

#last_responseObject (readonly)

Returns the value of attribute last_response.



15
16
17
# File 'lib/retab/types/list_struct.rb', line 15

def last_response
  @last_response
end

#list_metadataObject (readonly)

Returns the value of attribute list_metadata.



15
16
17
# File 'lib/retab/types/list_struct.rb', line 15

def 
  @list_metadata
end

Class Method Details

.from_response(response, model: nil, filters: {}, fetch_next: nil) ⇒ Object

Construct a ListStruct from an HTTP response with ‘[…], list_metadata: {…}`.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/retab/types/list_struct.rb', line 40

def self.from_response(response, model: nil, filters: {}, fetch_next: nil)
  _ = filters
  body = response.respond_to?(:body) ? response.body : response
  parsed = body.is_a?(String) ? JSON.parse(body) : (body || {})
  raw_items = parsed['data'] || parsed[:data] || []
  items = raw_items.map { |item| model ? model.new(item) : item }
  meta = parsed['list_metadata'] || parsed[:list_metadata] || {}
  api_response =
    if response.respond_to?(:code)
      ApiResponse.new(
        http_status: response.code.to_i,
        http_headers: response.respond_to?(:each_header) ? response.each_header.to_h : {},
        request_id: response.respond_to?(:[]) ? response['x-request-id'] : nil,
      )
    end
  new(data: items, list_metadata: meta, last_response: api_response, fetch_next: fetch_next)
end

Instance Method Details

#each(&block) ⇒ Object



24
25
26
# File 'lib/retab/types/list_struct.rb', line 24

def each(&block)
  @data.each(&block)
end

#has_next?Boolean

Returns:

  • (Boolean)


28
29
30
31
# File 'lib/retab/types/list_struct.rb', line 28

def has_next?
  cursor = @list_metadata.is_a?(Hash) ? (@list_metadata[:after] || @list_metadata['after']) : nil
  !cursor.nil? && !cursor.to_s.empty?
end

#next_pageObject



33
34
35
36
37
# File 'lib/retab/types/list_struct.rb', line 33

def next_page
  return nil unless has_next? && @fetch_next
  cursor = @list_metadata[:after] || @list_metadata['after']
  @fetch_next.call(cursor)
end