Module: FulfilApi::Resource::AttributeAssignable

Included in:
FulfilApi::Resource
Defined in:
lib/fulfil_api/resource/attribute_assignable.rb

Overview

The AttributeAssignable module provides a set of helper

methods to assign and cast attributes (including their values) to a {FulfilApi::Resource}.

Instance Method Summary collapse

Instance Method Details

#assign_attribute(name, value) ⇒ Hash

Assigns and casts a single attribute for the FulfilApi::Resource.

Parameters:

  • name (String, Symbol)

    The attribute name

  • value (Any)

    The attribute value

Returns:

  • (Hash)

    The resource attributes



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/fulfil_api/resource/attribute_assignable.rb', line 25

def assign_attribute(name, value) # rubocop:disable Metrics/MethodLength
  attribute = build_attribute(name, value)
  attribute.deep_stringify_keys!

  # NOTE: Fulfil will assign the ID of a nested resource to its own namespace.
  #   This leads to conflicts when we're trying to parse the returned fields
  #   from the API.
  #
  # To address this problem, we're manually handling these cases. We're dealing
  #   with a nested relation when one of the values is an integer and the other
  #   is an hash.
  #
  # @example a nested relation
  #
  #   $ resource.assign_attributes({ "warehouse.name" => "Toronto", "warehouse" => 10 })
  #   => <FulfilApi::Resource @attributes={"warehouse" => { "id" => 10, "name" => "Toronto" }} />
  @attributes = @attributes.deep_merge(attribute) do |_key, current_value, other_value|
    if current_value.is_a?(Integer) && other_value.is_a?(Hash)
      { "id" => current_value }.deep_merge(other_value)
    elsif current_value.is_a?(Hash) && other_value.is_a?(Integer)
      current_value.deep_merge({ "id" => other_value })
    else
      other_value
    end
  end
end

#assign_attributes(attributes) ⇒ Hash

Assigns and casts a set of attributes for the FulfilApi::Resource

Parameters:

  • attributes (Hash)

    The assignable attributes

Returns:

  • (Hash)

    The resource attributes



12
13
14
15
16
17
18
# File 'lib/fulfil_api/resource/attribute_assignable.rb', line 12

def assign_attributes(attributes)
  attributes.each_pair do |key, value|
    assign_attribute(key, value)
  end

  @attributes
end