Sha256: 571d1b149706c93070f35ed03445394c3db58ead7d217178c6950959b569c25b

Contents?: true

Size: 1.88 KB

Versions: 1

Compression:

Stored size: 1.88 KB

Contents

module Mooamba
  module Correios
    API_URL = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?"
  end

  class Sedex
    include SAXMachine

    CODE = 40010

    DEFAULT_PARAMS = {
      :nCdServico => CODE,
      :StrRetorno => "XML"
    }

    element "Valor", :as => :price
    element "Erro", :as => :error
    element "cServico", :as => :service

    def self.calculate(options={})
      raise InvalidOriginZipCode if invalid_cep?(options[:from])
      raise InvalidDestinationZipCode if invalid_cep?(options[:to])
      raise InvalidWeight if invalid_weight?(options[:weight])
      response = response_for options
      error?(response) ? (raise exception(response)) : response
    end

    private

    def self.parameters_from(options)
      translate(options).merge DEFAULT_PARAMS
    end

    def self.translate(options)
      { :sCepOrigem => options[:from].clean,
        :sCepDestino => options[:to].clean,
        :nVlPeso => options[:weight] }
    end

    def self.response_for(options)
      parse open(URI.escape(Correios::API_URL + parameters_from(options).to_query_string)).read
    end

    def self.exception(response)
      if response.service.nil?
        Mooamba::UnavailableAPI
      else
        case response.error
        when "-2"; Mooamba::Correios::InvalidOriginZipCode
        when "-3"; Mooamba::Correios::InvalidDestinyZipCode
        when "-4"; Mooamba::Correios::ExcessiveWeight
        when "-6"; Mooamba::Correios::UnavailableServiceForArea
        when "-10"; Mooamba::Correios::UnavailableServiceForArea
        when "7"; Mooamba::Correios::UnavailableService
        else; Mooamba::Correios::UnknownError
        end
      end
    end

    def self.error?(response)
      response.error != "0"
    end

    def self.invalid_cep?(cep)
      cep.blank? or cep.invalid?
    end

    def self.invalid_weight?(weight)
      weight.blank? or weight.to_i <= 0
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mooamba-0.0.2 lib/mooamba/sedex.rb