Class: DutyCalculator::Calculation

Inherits:
Object
  • Object
show all
Defined in:
lib/duty_calculator/calculation.rb

Class Method Summary collapse

Class Method Details

.get(params = {}) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/duty_calculator/calculation.rb', line 39

def self.get(params={})
  transformed_params = transform_params(validate_params(params))
  # initialize connection
  conn = DutyCalculator::Client.new

  resp = conn.get "#{DutyCalculator::Client.api_base}/calculation", transformed_params
  hashed_resp = DutyCalculator::Response.new(resp.to_hash)
  resp = Hashie::Mash.new(hashed_resp)

  if resp.body["error"]
    return DutyCalculator::Dootie.new({message: "[DutyCalculator][Error]:", error: resp.body["error"]})
  end

  resp.body.duty_calculation
end

.transform_params(params) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/duty_calculator/calculation.rb', line 22

def transform_params(params)
  params.inject({}) do |transformed, key_value|
    k = key_value.first
    v = key_value.last
    if v.kind_of?(Array)
      transformed[k] = {}
      v.each_with_index do |value, index|
        transformed[k][index] = value
      end
    else
      transformed[k] = v
    end
    transformed
  end
end

.validate_params(params) ⇒ Object

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/duty_calculator/calculation.rb', line 8

def validate_params(params)
  required = %w{from to shipping_mode shipping
                insurance currency preferential_rates detailed_result incl_hs_codes cat
                hs country_of_hs_code desc
                sku value weight qty origin reference}
  msg = []
  required.each do |r|
    # ensure keys are strings
    msg << r unless params.inject({}){|memo,(k,v)| memo[k.to_s] = v; memo}.has_key?(r)
  end
  raise ArgumentError, "Missing arguments from hash #{msg.to_s}" if msg.size >= 1
  return params
end