forked from dgilperez/validates_zipcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatter.rb
53 lines (50 loc) · 1.4 KB
/
formatter.rb
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
# frozen_string_literal: true
module ValidatesZipcode
class Formatter
WORD_CHAR_AND_DIGIT = /[A-Z0-9]/.freeze
ZIPCODES_TRANSFORMATIONS = {
AT: ->(z) { z.scan(/\d/).join },
ES: :AT,
CA: ->(z) { z.upcase.scan(WORD_CHAR_AND_DIGIT).insert(3, ' ').join },
CZ: ->(z) { z.scan(/\d/).insert(3, ' ').join },
DE: ->(z) {
digits = z.scan(/\d/)
result = digits.join
result.prepend('0') if digits.count < 5
result
},
GB: ->(z) { z.upcase.scan(WORD_CHAR_AND_DIGIT).insert(-4, ' ').join },
NL: ->(z) { z.upcase.scan(WORD_CHAR_AND_DIGIT).insert(4, ' ').join },
PL: ->(z) { z.scan(/\d/).insert(2, '-').join },
SK: :CZ,
UK: :GB,
MT: :GB,
FK: :GB,
GS: :GB,
PN: :GB,
SH: :GB,
TC: :GB,
GI: :GB,
US: ->(z) {
digits = z.scan(/\d/)
digits.insert(5, '-') if digits.count > 5
digits.join
}
}.freeze
def initialize(args = {})
@zipcode = args.fetch(:zipcode).to_s
@country_alpha2 = args.fetch(:country_alpha2).to_s.upcase.to_sym
end
def format
transformation = ZIPCODES_TRANSFORMATIONS[@country_alpha2]
case transformation
when Proc
transformation.call(@zipcode)
when Symbol
ZIPCODES_TRANSFORMATIONS[transformation].call(@zipcode)
else
@zipcode.strip
end
end
end
end