Class: ViaCep::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/viacep/service.rb

Constant Summary collapse

BASE_URL =
'https://viacep.com.br/ws'.freeze

Class Method Summary collapse

Class Method Details

.fetch(cep, timeout) ⇒ Hash

Fetches the ViaCEP API to request a CEP.

Examples:

Fetch a CEP with no timeout.

ViaCep::Service.fetch('80210130', nil)
#=> {"cep"=>"80210-130", "logradouro"=>"Rua José Ananias Mauad", "complemento"=>"", "bairro"=>"Jardim Botânico", "localidade"=>"Curitiba", "uf"=>"PR", "unidade"=>"", "ibge"=>"4106902", "gia"=>""}

Fetch a CEP with a timeout of 30 seconds.

ViaCep::Service.fetch('80210130', 30)
#=> {"cep"=>"80210-130", "logradouro"=>"Rua José Ananias Mauad", "complemento"=>"", "bairro"=>"Jardim Botânico", "localidade"=>"Curitiba", "uf"=>"PR", "unidade"=>"", "ibge"=>"4106902", "gia"=>""}

Parameters:

  • cep (String)

    The CEP to be fetched.

  • timeout (Integer, nil)

    The timeout in seconds for the request to be finished.

Returns:

  • (Hash)

Raises:

  • (ViaCep::ApiRequestError)

    This is raised when the external API is down or the CEP does not exist.

  • (Timeout::Error)

    This is raised when the timeout argument is specified and the request timed out.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/viacep/service.rb', line 30

def self.fetch(cep, timeout)
  Timeout.timeout(timeout) do
    uri = URI("#{BASE_URL}/#{cep}/json")
    request = Net::HTTP.get_response(uri)

    if request.code == '200'
      response = JSON.parse(request.body)

      if response["erro"]
        raise ApiRequestError, "The server responded with HTTP 200 could not process the request"
      end

      response
    else
      raise ApiRequestError, "The server responded with HTTP #{request.code}"
    end
  end
end