1
2
3
4
5
6
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
# frozen_string_literal: true
require_relative "cepis/version"
require_relative "cepis/errors"
require_relative "cepis/models"
require_relative "cepis/client"
# Ruby client for the public CEP API at https://cep.is.
#
# For a script, the module-level methods are enough:
#
# require "cepis"
#
# address = Cepis.lookup("01001-000")
# puts "#{address.localidade} #{address.uf}" # São Paulo SP
#
# In an application, build a {Cepis::Client} once and reuse it:
#
# client = Cepis::Client.new(timeout: 5.0, total_timeout: 15.0)
# address = client.lookup("01001000")
#
# Pointing at a local instance (the API repo brings one up with `just up`):
#
# client = Cepis::Client.new(base_url: "http://localhost:8080")
#
# Errors are explicit and split by decision — whether retrying helps or not:
#
# begin
# address = Cepis.lookup(cep_from_form)
# rescue Cepis::CEPNotFound => e
# # the CEP does not exist: ask the user for another. e.faixa, when the
# # API sends it, names the municipality whose numbers surround the one
# # that failed — context for the error, never an address.
# puts "did you mean somewhere in #{e.faixa.localidade}?" if e.faixa
# rescue Cepis::Error
# # network, server, rate limit: retry later
# end
#
# Note on field names: the API surface is English, but the **data fields keep
# the API's own Portuguese names** (`logradouro`, `bairro`, `localidade`). What
# you read in the JSON is what you read on the object.
module Cepis
class << self
# The client behind the module-level methods.
#
# It is built once because {Client} keeps no state between calls and is
# safe to share across threads. It applies process-wide, including to
# third-party libraries that also use this module — anyone needing
# different settings should build their own {Client}.
#
# @return [Client]
def default_client
@default_client ||= Client.new
end
# Look up a CEP using the default configuration.
#
# Shorthand for `Cepis.default_client.lookup(cep)`. See {Client#lookup}.
#
# @param cep [String]
# @return [Address]
def lookup(cep)
default_client.lookup(cep)
end
# Look up many CEPs in one batch, using the default configuration.
#
# Shorthand for {Client#lookup_many} — read that one, especially the
# warning that batches carry no coordinate.
#
# @param ceps [Array<String>]
# @return [Array<Address, nil>]
def lookup_many(ceps)
default_client.lookup_many(ceps)
end
# Query the API's health using the default configuration.
#
# Shorthand for {Client#health}.
#
# @return [Health]
def health
default_client.health
end
end
end
|