Class: LemonSqueezy::Collection

Inherits:
Object
  • Object
show all
Defined in:
lib/lemon_squeezy/collection.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data:, meta:, total:) ⇒ Collection

Returns a new instance of Collection.



36
37
38
39
40
# File 'lib/lemon_squeezy/collection.rb', line 36

def initialize(data:, meta:, total:)
  @data = data
  @meta = meta
  @total = total
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



3
4
5
# File 'lib/lemon_squeezy/collection.rb', line 3

def data
  @data
end

#metaObject (readonly)

Returns the value of attribute meta.



3
4
5
# File 'lib/lemon_squeezy/collection.rb', line 3

def meta
  @meta
end

#totalObject (readonly)

Returns the value of attribute total.



3
4
5
# File 'lib/lemon_squeezy/collection.rb', line 3

def total
  @total
end

Class Method Details

.from_response(response, type:, key: nil) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/lemon_squeezy/collection.rb', line 5

def self.from_response(response, type:, key: nil)
  body = response.body

  if key.is_a?(String)
    data  = body["data"][key].map { |attrs| type.new(attrs) }
    total = body["data"]["total"]
  else
    data  = body["data"].map { |attrs| type.new(attrs) }
    total = body["data"].count
  end

  # Extract pagination metadata if available
  meta = body["meta"]
  pagination = meta&.dig("page")
  
  new(
    data: data,
    meta: {
      page: {
        total: pagination&.dig("total"),
        current_page: pagination&.dig("currentPage"),
        from: pagination&.dig("from"),
        to: pagination&.dig("to"),
        last_page: pagination&.dig("lastPage"),
        per_page: pagination&.dig("perPage")
      }
    },
    total: total
  )
end