Class: BrZipCode::Service::CepLivre
Instance Attribute Summary
#response, #response_body, #zip_code
Instance Method Summary
collapse
#basic_valid?
Constructor Details
#initialize(zip_code, no_timeout = false) ⇒ CepLivre
Returns a new instance of CepLivre.
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
# File 'lib/br_zip_code/service/cep_livre.rb', line 7
def initialize zip_code, no_timeout = false
raise 'Environment Variable CEP_LIVRE_TOKEN not set.' if ENV['CEP_LIVRE_TOKEN'].nil?
@zip_code = zip_code.to_s.gsub(/[^0-9]/, '')
return unless self.basic_valid?
@zip_code = @zip_code[0..4] + '-' + @zip_code[5..-1]
if no_timeout
@response = HTTParty.get(final_url)
else
@response = HTTParty.get(final_url, timeout: BrZipCode.timeout)
end
@response_body = @response.response.body
if self.valid?
xml = Nokogiri.XML(@response_body)
children = xml.xpath("//cep").children
names = children.map { |x| x.name }
values = children.map { |x| x.children }.flatten.map { |x| x.text }
h = Hash[names.zip values]
@response_body = {
'ceplivre' => {
'cep' => h
}
}
end
end
|
Instance Method Details
#base_url ⇒ Object
61
62
63
|
# File 'lib/br_zip_code/service/cep_livre.rb', line 61
def base_url
"http://ceplivre.com.br/consultar/cep/#{ENV['CEP_LIVRE_TOKEN']}/"
end
|
#final_url ⇒ Object
57
58
59
|
# File 'lib/br_zip_code/service/cep_livre.rb', line 57
def final_url
"#{base_url}#{self.zip_code}/xml"
end
|
#to_hash ⇒ Object
40
41
42
43
44
45
46
47
48
49
50
51
|
# File 'lib/br_zip_code/service/cep_livre.rb', line 40
def to_hash
return nil unless self.valid?
cep_body = response_body['ceplivre']['cep']
{
street: [cep_body['tp_logradouro'],cep_body['logradouro']].join(' '),
district: cep_body['bairro'],
city: cep_body['cidade'],
state: cep_body['uf_sigla']
}
end
|
#valid? ⇒ Boolean
53
54
55
|
# File 'lib/br_zip_code/service/cep_livre.rb', line 53
def valid?
super and self.response.code == 200 and not self.response_body == '' and not self.response_body['ceplivre'].nil?
end
|