Sha256: e9f08a1b646551d69449f47182627770f73dfeb6097c4d0acdd2e6af113c25e6

Contents?: true

Size: 1.61 KB

Versions: 1

Compression:

Stored size: 1.61 KB

Contents

require "duty_calculator/client"
require "addressable/uri"
module DutyCalculator
  class Calculation
    class << self
      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

      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
    end

    def self.get(params={})
      transformed_params = transform_params(validate_params(params))
      conn = DutyCalculator::Client.new
      resp = conn.get "#{DutyCalculator::Client.api_base}/calculation", transformed_params
      raise Exception, "Duty Calculator Error: #{DutyCalculator::ErrorMessages.for_code(resp.body["error"]["code"])}" if resp.body["error"]
      raise Exception, "HTTP Status Code #{resp.status}" if resp.status.to_i != 200
      return resp.body
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
duty_calculator-0.0.5 lib/duty_calculator/calculation.rb