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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# 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" }} />
  #
  # @example a nested relation with a string as ID
  #
  #   $ resource.assign_attributes({ "shipment" => "stock.shipment.out,12", "shipment.number": "CS1234" })
  #   => <FulfilApi::Resource @attributes={"warehouse" => { "id" => 12, "number" => "CS1234" }} />
  @attributes = @attributes.deep_merge(attribute) do |_key, current_value, other_value|
    extract_id = lambda { |possible_id|
      possible_id =~ /\A[\w-]+(?:\.[\w-]+){1,2},(?<id>\d+)\z/ ? Regexp.last_match[:id].to_i : nil
    }

    case [current_value, other_value]
    in [String => str, Hash] if (id = extract_id.call(str))
      { "id" => id }.merge(other_value)
    in [Integer, Hash]
      { "id" => current_value }.merge(other_value)
    in [Hash, Integer]
      current_value.merge({ "id" => other_value })
    in [Hash, String => str] if (id = extract_id.call(str))
      current_value.merge({ "id" => id })
    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