Sha256: 1a82bdef05bf99187ef1e1b6c1b3a01adf86f4e5ce292be6919ef4da32f2473b

Contents?: true

Size: 1.67 KB

Versions: 1

Compression:

Stored size: 1.67 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])
      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

Version data entries

1 entries across 1 versions & 1 rubygems

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