Class: FulfilApi::Resource::AttributeType

Inherits:
Object
  • Object
show all
Defined in:
lib/fulfil_api/resource/attribute_type.rb

Overview

The AttributeType enables parsing any attribute value

returned by the Fulfil API. To preserve type information Fulfil extends the JSON format.
When the response value is extended, it is considered castable.

For all possible special

Examples:

an extended attribute value (date)

$ AttributeType.cast({ "__class__" => "date", "iso_string" => "2024-12-12" })
=> #<Date: 2024-08-30 />

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ AttributeType

Returns a new instance of AttributeType.

Parameters:

  • value (Any)


27
28
29
30
# File 'lib/fulfil_api/resource/attribute_type.rb', line 27

def initialize(value)
  @type = extended?(value) ? value.fetch("__class__") : nil
  @value = value
end

Class Method Details

.cast(value) ⇒ Any

Casts any attribute value to its final form.

Parameters:

  • value (Any)

    The attribute value to cast

Returns:

  • (Any)

    The casted attribute value



22
23
24
# File 'lib/fulfil_api/resource/attribute_type.rb', line 22

def self.cast(value)
  new(value).cast_value
end

Instance Method Details

#cast_valueAny

Casts the attribute value to an useable format for a Ruby application.

Returns:

  • (Any)


35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/fulfil_api/resource/attribute_type.rb', line 35

def cast_value
  case @type
  when "bytes" then Base64.decode64(value_before_cast)
  when "date" then Date.parse(value_before_cast)
  when "datetime" then DateTime.parse(value_before_cast)
  when "decimal" then BigDecimal(value_before_cast)
  when "time" then Time.parse(value_before_cast)
  when "timedelta" then value_before_cast
  else
    @value
  end
end

#value_before_castAny

Retrieves the raw attribute value.

Returns:

  • (Any)


51
52
53
54
55
56
57
58
59
# File 'lib/fulfil_api/resource/attribute_type.rb', line 51

def value_before_cast
  case @type
  when "bytes" then @value["base64"]
  when "date", "datetime", "time", "timedelta" then @value["iso_string"]
  when "decimal" then @value["decimal"]
  else
    @value
  end
end