Skip to content

Commit

Permalink
Version 2.0.0 is out! 😏
Browse files Browse the repository at this point in the history
  • Loading branch information
Rodrigo Alves committed Jul 6, 2013
1 parent 8129672 commit ee8d150
Show file tree
Hide file tree
Showing 8 changed files with 134 additions and 163 deletions.
7 changes: 1 addition & 6 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,2 @@
if RUBY_VERSION =~ /1.9/
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8
end

source "http://rubygems.org"
gemspec
gemspec
7 changes: 7 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright (c) 2012-2013 Rodrigo Alves

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to use, copy and modify copies of the Software, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
84 changes: 15 additions & 69 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
# CepFacil

Ruby wrapper para o serviço em [cepfacil.com.br]
Wrapper Ruby para a API do [CepFácil]

[![Code Climate](https://codeclimate.com/badge.png)](https://codeclimate.com/github/rodrigoalvesvieira/cep_facil)
[![Build Status](https://secure.travis-ci.org/rodrigoalvesvieira/cep_facil.png?branch=master)](http://travis-ci.org/rodrigoalvesvieira/cep_facil)
* [![Dependencies](https://gemnasium.com/rodrigoalvesvieira/cepfacil.png?travis)](https://gemnasium.com/rodrigoalvesvieira/cepfacil)

## Instalação

Expand All @@ -13,7 +14,6 @@ No `Gemfile`:

```ruby
gem "cep_facil"

```

Ou via RubyGems, diretamente:
Expand All @@ -27,32 +27,23 @@ Ou via RubyGems, diretamente:
Para usar a API do [CepFácil], você precisa obter um token do serviço. Você obtém esse token gratuitamente em cepfacil.com.br

```ruby

require "cep_facil"

cep = "53417-540"
# Autenticando

token = "1234567890"
conn = CepFacil::API.new token

address = CepFacil::API.new(cep, token)

### Acesso rápido via método de classe

address = CepFacil::API.get(cep, token) # Hash Notation => CepFacil::API.get(cep: cep, token: token)

# Argumentos como Hashes

address = CepFacil::API.new(cep: cep, token: token, format: "texto")
# Obtendo endereços

zip_code = "53416540"
address = conn.get_address(zip_code)
```

#### Retorna o endereço referente àquele CEP
#### Retorna o endereço (objeto `CepFacil::Address`) referente àquele CEP

O retorno é um objeto `CepFacil::API` que contem os seguintes métodos (propriedades) :

```ruby


address.cep # => "53417540"

address.type # => "Rua"
Expand All @@ -64,62 +55,25 @@ address.city # => "Paulista"
address.neighborhood # => "Artur Lundgren II"

address.street # => "Panelas"

# Também é possivel acessar utilizando metodos em português

address.tipo # => "Avenida"

address.rua # => "Francisco Navarro"

address.cidade # => "Varginha"

address.bairro # => "Centro"

address.estado # => "MG"

address.uf # => "MG"

```

Embora isso deva parecer óbvio, informo que essas propriedades são todas **READONLY**.

Você pode checar se o endereço retornado é válido utilizando o método `valid?`:

```ruby

address = CepFacil::API.new "53020-140", token

address.valid? # true

```

Você também pode checar se o endereço foi encontrado com o CEP passado da seguinte forma:
Adicionalmente, seu objeto `CepFacil::Address` possui um método `full_format` que o descreve por extenso:

```ruby

address = CepFacil::API.new "53417-540", token

address.found? # true

address = CepFacil::API.new "00000000", token

address.valid? # false

address.full_format # => "RUA PANELAS, PAULISTA - PE 53416540, Brasil"
```

Adicionalmente, seu objeto `CepFacil::API` possui um método `full_format` e seu alias (`full_address`) que o descreve por extenso:

```ruby

address.full_format # => "Rua Panelas, Paulista - PE, Brasil"

address.full_address # => Avenida Francisco Navarro, Varginha - MG, Brasil" # Alias

```
Você pode passar o CEP como uma string qualquer, letras, caracteres especiais (pontos, hífens) são removidos automaticamente.

```ruby

"12345-678"
"123.45.678"
"123-456.78"
Expand All @@ -132,39 +86,31 @@ Você pode passar o CEP como uma string qualquer, letras, caracteres especiais (
A gem [Geocoder] é ótima para uso e manipulação de dados geográficos em projetos Ruby. Para integrá-la com o CepFacil, faça assim:

```ruby

geocoded_by address.full_format

```

## Autor

* Rodrigo Alves - [email protected] - http://www.rodrigoalvesvieira.com
* Rodrigo Alves

## Contribuidores

* Adriano Bacha - [email protected]
* Rafael Fidelis - [email protected] | http://defidelis.com
* Adriano Bacha
* Rafael Fidelis

## Agradecimentos

Obrigado pelas pessoas que oferecem o serviço [CepFácil], sem o qual esse projeto não seria possível.

Obrigado também aos [Contribuidores] desse projeto.

## Doações

Se esse projeto é tão útil para você que lhe faz considerar fazer alguma doação, ao invés de me pagar uma cerveja
(o que seria um boa ideia, com certeza) considere doar para o [Khan Academy].

## Licença

CepFacil é liberado sob a [licença do MIT] com atribuições a Rodrigo Alves.
CepFacil é liberado sob a [licença do MIT] com atribuições a Rodrigo Alves. Para detalhes veja o arquivo LICENSE.txt

[0x]: https://github.com/rodrigoalvesvieira/cep_facil/tree/0x
[Geocoder]: https://github.com/alexreisner/geocoder
[CepFácil]: http://cepfacil.com.br
[cepfacil.com.br]: http://cepfacil.com.br
[Contribuidores]: #contribuidores
[licença do MIT]: http://pt.wikipedia.org/wiki/Licen%C3%A7a_MIT#Texto_da_licen.C3.A7a
[Khan Academy]: https://www.khanacademy.org/
[licença do MIT]: http://pt.wikipedia.org/wiki/Licen%C3%A7a_MIT#Texto_da_licen.C3.A7a
35 changes: 20 additions & 15 deletions cep_facil.gemspec
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "cep_facil/version"

Gem::Specification.new do |s|
s.name = "cep_facil"
s.version = CepFacil::VERSION
s.authors = ["Rodrigo Alves Vieira"]
s.email = ["[email protected]"]
s.homepage = "http://github.com/rodrigoalvesvieira/cep_facil"
s.summary = %q{Wrapper para o serviço cepfacil.com.br}
s.description = %q{Wrapper Ruby para o serviço cepfacil.com.br}
s.name = "cep_facil"
s.version = CepFacil::VERSION
s.authors = ["Rodrigo Alves"]
s.email = ["[email protected]"]
s.homepage = "http://github.com/rodrigoalvesvieira/cep_facil"
s.summary = %q{Wrapper para o serviço cepfacil.com.br}
s.description = %q{Wrapper Ruby para o serviço cepfacil.com.br}
s.rubyforge_project = "cep_facil"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_dependency("rake", "0.9.2.2")
s.add_development_dependency("rspec", "~> 2.10.0")
end
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]

s.rdoc_options = ["--title", "Wrapper Ruby para a API do CepFacil", "--main", "README.md"]
s.licenses = ["MIT"]

s.add_dependency("rake", "~> 10.1.0")
s.add_dependency("json", "~> 1.8.0")

s.add_development_dependency("rspec", "~> 2.13.0")
end
3 changes: 2 additions & 1 deletion lib/cep_facil.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#--
# Copyright (c) 2012 Rodrigo Alves Vieira
# Copyright (c) 2012-2013 Rodrigo Alves
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
Expand All @@ -22,6 +22,7 @@
#++

require "cep_facil/version"

module CepFacil
autoload :API, "cep_facil/api"
end
100 changes: 60 additions & 40 deletions lib/cep_facil/api.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,58 @@
# encoding: utf-8
#--
# Copyright (c) 2012-2013 Rodrigo Alves
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++

require "net/http"
require "json"

module CepFacil
class Address
attr_accessor :zip_code, :type, :city, :state, :neighborhood, :street

def initialize(zip_code, type, city, state, neighborhood, street)
@zip_code = zip_code
@type = type
@city = city
@state = state
@neighborhood = neighborhood
@street = street
end

def valid?
answ = false
answ = true if (self.zip_code && type && city)
return true
end

# Returns the address in its extense format
def full_format
"#{self.type} #{self.street}, #{self.city} - #{self.state} #{self.zip_code}, Brasil"
end
end

class API
attr_reader :read
attr_accessor :token

BASE_URL = "http://www.cepfacil.com.br/service/?filiacao=%s&cep=%s&formato=%s"
BASE_URL = "http://www.cepfacil.com.br/service/?filiacao=%s&cep=%s&formato=json"
PLACEHOLDER_METHODS = {
estado: :uf,
type: :tipo,
Expand All @@ -24,47 +71,20 @@ def parse_zip_code(zip_code)
end
end

def initialize(*args)
args = (args[0].is_a?(Hash) ? args[0] : Hash[[:cep,:token,:format].zip(args)])
args[:format] ||= "texto"
args[:cep] = CepFacil::API.parse_zip_code(args[:cep])

uri = URI(BASE_URL % [args[:token], args[:cep], args[:format]])
@read = Net::HTTP.get(uri)
@data = args[:format].to_s == "texto" ? Hash[@read.split("&").map { |i| i.split("=") } ] : @read

# OPTIMIZE: Need a better implementation
return self
def initialize(token)
@token = token
end

# Returns true if the address in question is a valid one
# returns false otherwise
def valid?
@data.is_a?(Hash) and @data.size > 1
end
def get_address(zip_code)
uri = URI(BASE_URL % [self.token, CepFacil::API.parse_zip_code(zip_code)])
content = Net::HTTP.get(uri)

# Returns the address in its extense format
def full_format
"#{type} #{street}, #{city} - #{state}, Brasil"
end

# Returns true if the address was found with the given zip code (CEP)
# returns false otherwise
def found?
self.status == "encontrado"
end

def self.get(*args)
self.new(*args)
end
result = JSON.parse content

private
# Define placeholder methods for the address attributes
# in pt-BR
def method_missing(*args)
return (@data[PLACEHOLDER_METHODS[args[0].to_sym].to_s] || @data[args[0].to_s]).force_encoding(Encoding::UTF_8) || super(*args)
address = CepFacil::Address.new(
result["CEP"], result["LogradouroTipo"],
result["Cidade"], result["UF"], result["Bairro"], result["Logradouro"])
end

alias :address :full_format
end
end
end
4 changes: 2 additions & 2 deletions lib/cep_facil/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module CepFacil
VERSION = "1.0.4" #:nodoc:
end
VERSION = "2.0.0" #:nodoc:
end
Loading

0 comments on commit ee8d150

Please sign in to comment.