Class: ValidatesZipcode::Validator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/validates_zipcode/validator.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Validator

Returns a new instance of Validator.



19
20
21
22
23
24
# File 'lib/validates_zipcode/validator.rb', line 19

def initialize(options)
  @country_code           = options.fetch(:country_code) { }
  @country_code_attribute = options.fetch(:country_code_attribute) { :country_alpha2 }

  super
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/validates_zipcode/validator.rb', line 26

def validate_each(record, attribute, value)
  alpha2 = @country_code || record.send(@country_code_attribute)

  unless ValidatesZipcode::Zipcode.new(zipcode: value.to_s, country_alpha2: alpha2).valid?
    record.errors.add(attribute, I18n.t('errors.messages.invalid_zipcode', value: value))
  end
end