Skip to content

Commit b208093

Browse files
committed
feat: add validation method
1 parent ead63ca commit b208093

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

lib/brazil_cep.rb

+3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
require_relative "brazil_cep/version"
44
require_relative "brazil_cep/address"
55
require_relative "brazil_cep/adapters"
6+
require_relative "brazil_cep/validation"
67

78
module Brazil
89
# Brazil::Cep providers a simple way to fetch address information from a Brazilian CEP
@@ -27,6 +28,8 @@ def initialize(response)
2728
# zipcode not found error class
2829
class ZipcodeNotFound < RequestError; end
2930

31+
include Validation
32+
3033
# fetch address information from a Brazilian CEP
3134
# @param [String] cep the CEP to fetch
3235
# @return [Hash] the address information

lib/brazil_cep/validation.rb

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# frozen_string_literal: true
2+
3+
4+
module Brazil
5+
module Cep
6+
# CEP ranges by state
7+
RANGES = {
8+
"AC" => (69900000..69999999),
9+
"AL" => (57000000..57999999),
10+
"AP" => (68900000..68999999),
11+
"AM" => (69000000..69299999),
12+
"BA" => (40000000..48999999),
13+
"CE" => (60000000..63999999),
14+
"DF" => (70000000..73699999),
15+
"ES" => (29000000..29999999),
16+
"GO" => (72800000..76799999),
17+
"MA" => (65000000..65999999),
18+
"MT" => (78000000..78899999),
19+
"MS" => (79000000..79999999),
20+
"MG" => (30000000..39999999),
21+
"PA" => (66000000..68899999),
22+
"PB" => (58000000..58999999),
23+
"PR" => (80000000..87999999),
24+
"PE" => (50000000..56999999),
25+
"PI" => (64000000..64999999),
26+
"RJ" => (20000000..28999999),
27+
"RN" => (59000000..59999999),
28+
"RS" => (90000000..99999999),
29+
"RO" => (76800000..76999999),
30+
"RR" => (69300000..69399999),
31+
"SC" => (88000000..89999999),
32+
"SP" => (01000000..19999999),
33+
"SE" => (49000000..49999999),
34+
"TO" => (77000000..77999999)
35+
}.freeze
36+
37+
# Validation module
38+
module Validation
39+
def self.included(base)
40+
base.extend(ClassMethods)
41+
end
42+
43+
module ClassMethods
44+
def valid?(cep)
45+
cep = cep.to_s.gsub(/\D/, "")
46+
return false if cep.size != 8
47+
48+
RANGES.values.any? do |group|
49+
group.cover?(cep.to_i)
50+
end
51+
end
52+
end
53+
end
54+
end
55+
end

spec/brazil_cep/validation_spec.rb

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# frozen_string_literal: true
2+
3+
require "spec_helper"
4+
5+
RSpec.describe Brazil::Cep do
6+
describe "#valid?" do
7+
subject(:validation) { Brazil::Cep.valid?(cep) }
8+
9+
context "when the CEP is valid" do
10+
let(:cep) { "88220-000" }
11+
12+
it { expect(validation).to be_truthy }
13+
end
14+
15+
context "when the CEP is invalid" do
16+
let(:cep) { "00000000" }
17+
18+
it { expect(validation).to be_falsey }
19+
end
20+
end
21+
end

0 commit comments

Comments
 (0)