Sha256: 1e506f66de51d9b79be04ed819d4e72f2565cd66271e393213b236e235ac7140

Contents?: true

Size: 708 Bytes

Versions: 1

Compression:

Stored size: 708 Bytes

Contents

require 'net/http'
require 'uri'
require 'json'
require 'timeout'
require 'exceptions'

module ViaCep
  class Service
    BASE_URL = 'https://viacep.com.br/ws'.freeze

    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
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
viacep-2.0.0 lib/service.rb