Class: ValidatesZipcode::Zipcode

Inherits:
Object
  • Object
show all
Includes:
CldrRegexpCollection
Defined in:
lib/validates_zipcode/zipcode.rb

Constant Summary

Constants included from CldrRegexpCollection

CldrRegexpCollection::ZIPCODES_REGEX

Instance Method Summary collapse

Methods included from CldrRegexpCollection

#regexp_for_country_alpha2

Constructor Details

#initialize(args = {}) ⇒ Zipcode

Returns a new instance of Zipcode.



6
7
8
9
10
11
# File 'lib/validates_zipcode/zipcode.rb', line 6

def initialize(args = {})
  @zipcode                = args.fetch(:zipcode)
  @country_alpha2         = args.fetch(:country_alpha2)
  @excluded_country_codes = args.fetch(:excluded_country_codes, [])
  @format                 = args.fetch(:format, false)
end

Instance Method Details

#formatObject



22
23
24
25
26
# File 'lib/validates_zipcode/zipcode.rb', line 22

def format
  raise InvalidZipcodeError, "invalid zipcode #{formatted_zip} for country #{@country_alpha2.to_s.upcase}" unless valid?

  formatted_zip
end

#valid?Boolean Also known as: validate

Returns:

  • (Boolean)


13
14
15
16
17
18
19
# File 'lib/validates_zipcode/zipcode.rb', line 13

def valid?
  return true if @excluded_country_codes.include?(@country_alpha2)
  return true unless regexp

  zipcode = @format ? formatted_zip : @zipcode
  !!(regexp =~ zipcode)
end