Module: IbgeLocalidades

Included in:
Cidade, Estado, Mesorregiao, Microrregiao, Regiao
Defined in:
lib/ibge-localidades.rb

Defined Under Namespace

Classes: Cidade, Estado, Mesorregiao, Microrregiao, Regiao

Constant Summary collapse

API_VERSION =
'v1'
MAIN_URL =
'https://servicodados.ibge.gov.br/api/' + API_VERSION + '/localidades'

Instance Method Summary collapse

Instance Method Details

#as_objects(resposta) ⇒ Object



19
20
21
22
23
24
# File 'lib/ibge-localidades.rb', line 19

def as_objects resposta
  return self.new(resposta) if resposta.is_a? Hash
  resposta.each_with_object([]) do |obj, arr|
    arr << self.new(obj)
  end
end

#buscar_por_relacionamento(*args) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/ibge-localidades.rb', line 26

def buscar_por_relacionamento *args
  args.each do |relacionamento|
    string_relacionamento = relacionamento.to_s
    define_singleton_method "listar_por_#{string_relacionamento}" do |id|
      as_objects get(Module.const_get("IbgeLocalidades::#{string_relacionamento.capitalize}::PATH") + id.to_s + self::PATH)
    end
  end
end

#find_by_id(id) ⇒ Object



39
40
41
# File 'lib/ibge-localidades.rb', line 39

def find_by_id id
  as_objects get(self::PATH + id.to_s)
end

#get(url) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/ibge-localidades.rb', line 9

def get(url)
  uri             = URI(MAIN_URL + url)
  resposta = JSON.parse(Net::HTTP.get(uri))

  return resposta
rescue StandardError => e
  return { 'error' => 'Ocorreu um erro.',
           'backtrace'=> e.backtrace.join("\n") }
end

#listarObject



35
36
37
# File 'lib/ibge-localidades.rb', line 35

def listar
  as_objects get(self::PATH)
end