Class: Prodigi::Object

Inherits:
OpenStruct
  • Object
show all
Defined in:
lib/prodigi/object.rb

Overview

Base object class for wrapping API responses

Converts Hash and Array responses into OpenStruct objects for convenient dot-notation access to attributes. Recursively processes nested structures.

Examples:

Accessing nested attributes

order = Prodigi::Order.new({ id: "ord_123", recipient: { name: "Robin" } })
order.id          #=> "ord_123"
order.recipient.name #=> "Robin"

Direct Known Subclasses

Order, Product, Quote

Instance Method Summary collapse

Constructor Details

#initialize(attributes) ⇒ Object

Initializes a new Prodigi object

Parameters:

  • attributes (Hash, Array, Object)

    The attributes to convert



19
20
21
# File 'lib/prodigi/object.rb', line 19

def initialize(attributes)
  super(to_ostruct(attributes))
end

Instance Method Details

#to_ostruct(obj) ⇒ OpenStruct, ...

Recursively converts hashes and arrays to OpenStruct objects

Parameters:

  • obj (Hash, Array, Object)

    The object to convert

Returns:

  • (OpenStruct, Array, Object)

    The converted object



27
28
29
30
31
32
33
34
35
# File 'lib/prodigi/object.rb', line 27

def to_ostruct(obj)
  if obj.is_a?(Hash)
    OpenStruct.new(obj.transform_values { |val| to_ostruct(val) })
  elsif obj.is_a?(Array)
    obj.map { |o| to_ostruct(o) }
  else # Assumed to be a primitive value
    obj
  end
end