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]) 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::InvalidWeight when "-6"; 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 end end