Class: Shippo::API::Transformers::List

Inherits:
Object
  • Object
show all
Defined in:
lib/shippo/api/transformers/list.rb

Overview

List Transformer: if it finds a key mapped to an array, this transformer coerces each element into an appropriate model class – if available. As a result, return from, eg. Shipment.create will contain rates key that will no longer be an array of hashes, but an array of Shippo::Rate instances.

Constant Summary collapse

MATCHERS =

MATCHERS contains a list of procs that are used to try, in order, to convert a key mapped to an array of hashes, into a word that represents an existing model.

Each matcher receives a key as a parameter, and (if matches) it extracts the candidate word to be attempted to constantize. For example, rates matcher will return rates as output.

[
  ->(key) {
    case key.to_sym
      when :items
        :customs_items
      else
        nil
    end
  },

  ->(key) {
    reg = /^([\w_]+)_list$/
    reg.match(key.to_s) ? reg.match(key.to_s)[1] : nil
  },

  ->(key) {
    reg = /^([\w_]+s)$/
    reg.match(key.to_s) ? reg.match(key.to_s)[1] : nil
  }
]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ List

Returns a new instance of List.



39
40
41
# File 'lib/shippo/api/transformers/list.rb', line 39

def initialize(hash)
  self.h = hash
end

Instance Attribute Details

#hObject

Returns the value of attribute h.



10
11
12
# File 'lib/shippo/api/transformers/list.rb', line 10

def h
  @h
end

Instance Method Details

#transformObject



43
44
45
46
47
48
# File 'lib/shippo/api/transformers/list.rb', line 43

def transform
  h.keys.each { |k| h[k].is_a?(Array) && !h[k].empty? }.each do |list_key|
    type, *values = transform_list(list_key, h[list_key])
    h[list_key]   = values if type
  end
end