Class: PostalCodeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/louche/validators/postal_code_validator.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ PostalCodeValidator

Returns a new instance of PostalCodeValidator.



2
3
4
5
6
7
# File 'lib/louche/validators/postal_code_validator.rb', line 2

def initialize(options)
  options.reverse_merge!(message: :invalid_postal_code)
  options.reverse_merge!(regex: /\A[a-z]\d[a-z]\d[a-z]\d\z/i)
  options.reverse_merge!(cleanup_regex: /[^a-z0-9]/i)
  super
end

Class Method Details

.format_code(postal_code, regex) ⇒ Object



18
19
20
# File 'lib/louche/validators/postal_code_validator.rb', line 18

def self.format_code(postal_code, regex)
  postal_code.try(:gsub, regex, '')
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



9
10
11
12
13
14
15
16
# File 'lib/louche/validators/postal_code_validator.rb', line 9

def validate_each(record, attribute, value)
  value = PostalCodeValidator.format_code(value, options.fetch(:cleanup_regex))
  record.send(:"#{attribute}=", value)

  unless value =~ options.fetch(:regex)
    record.errors.add(attribute, options.fetch(:message), value: value)
  end
end