Class: ViaCep::Address

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cep, options = {}) ⇒ ViaCep::Address

Initializes an instance of ViaCep::Address and fetches the CEP using the external API.

Examples:

Fetch a CEP

ViaCep::Address.new('80210130')
#=> #<ViaCep::Address:0x00007fe52a8a0568 @cep="80210-130", @address="Rua José Ananias Mauad", @neighborhood="Jardim Botânico", @city="Curitiba", @state="PR", @ibge="4106902", @gia="">

Fetch a CEP with a formatted string

ViaCep::Address.new('80210-130')
#=> #<ViaCep::Address:0x00007fe52a8a0568 @cep="80210-130", @address="Rua José Ananias Mauad", @neighborhood="Jardim Botânico", @city="Curitiba", @state="PR", @ibge="4106902", @gia="">

Options Hash (options):

  • :timeout (Integer)

    The timeout in seconds to the request.

Raises:

  • (ArgumentError)

    This is raised when CEP is nil.

  • (ArgumentError)

    This is raised when CEP format is invalid.

  • (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.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/viacep/address.rb', line 28

def initialize(cep, options = {})
  if cep.nil?
    raise ArgumentError, 'CEP cannot be nil'
  end

  cep = cep.to_s.delete('^0-9')

  if cep.length != 8
    raise ArgumentError, 'CEP must have 8 digits'
  end

  response = Service.fetch cep, options[:timeout]
  fill_from response
end

Instance Attribute Details

#addressObject (readonly)

Returns the value of attribute address.



5
6
7
# File 'lib/viacep/address.rb', line 5

def address
  @address
end

#cepObject (readonly)

Returns the value of attribute cep.



5
6
7
# File 'lib/viacep/address.rb', line 5

def cep
  @cep
end

#cityObject (readonly)

Returns the value of attribute city.



5
6
7
# File 'lib/viacep/address.rb', line 5

def city
  @city
end

#giaObject (readonly)

Returns the value of attribute gia.



5
6
7
# File 'lib/viacep/address.rb', line 5

def gia
  @gia
end

#ibgeObject (readonly)

Returns the value of attribute ibge.



5
6
7
# File 'lib/viacep/address.rb', line 5

def ibge
  @ibge
end

#neighborhoodObject (readonly)

Returns the value of attribute neighborhood.



5
6
7
# File 'lib/viacep/address.rb', line 5

def neighborhood
  @neighborhood
end

#stateObject (readonly)

Returns the value of attribute state.



5
6
7
# File 'lib/viacep/address.rb', line 5

def state
  @state
end