Class: MaskValidator

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

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ MaskValidator

This validator use the characters ‘a’, ‘9’ and ‘*’ to validate the format with regular expression

Example using in models:

validates :phone, :mask => "(99) 9999-9999"
validates :acronym, :mask => "***"

Where:

a - to letters (A-Z, a-z)
9 - to numbers (0-9)
* - to alphanumerics (A-Z, a-z, 0-9)


16
17
18
19
20
# File 'lib/mask_validator.rb', line 16

def initialize(options)
  @allow_nil, @allow_blank = options.delete(:allow_nil), options.delete(:allow_blank)

  super
end

Instance Method Details

#character_mapObject



42
43
44
# File 'lib/mask_validator.rb', line 42

def character_map
  { "9" => "[0-9]", "a" => "[a-zA-Z]", "*" => "[a-zA-Z0-9]" }
end

#mask_value_for(record = nil) ⇒ Object

Evaluate the options according with its class:

options[:with] = :custom_mask
options[:with] = Proc.new {|o| o.custom_mask}
options[:with] = "9a"

TODO: improve this



54
55
56
57
58
59
60
61
62
63
# File 'lib/mask_validator.rb', line 54

def mask_value_for(record=nil)
  case options[:with]
  when String
    options[:with]
  when Proc
    options[:with].call(record)
  when Symbol
    record.send(options[:with])
  end
end

#regexp(record = nil) ⇒ Object

Transform the string in a regular expression:

mask_value_for(record) => "9a"

regexp #=> /[0-9][a-zA-Z]/

TODO: improve this



38
39
40
# File 'lib/mask_validator.rb', line 38

def regexp(record=nil)
  /\A#{(mask_value_for(record).to_s.each_char.collect { |char| character_map[char] || "\\#{char}" }).join}\z/
end

#validate_each(record, attribute, value) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/mask_validator.rb', line 22

def validate_each(record, attribute, value)
  value = normalize_value(record, attribute, value)

  return if (@allow_nil && value.nil?) || (@allow_blank && value.blank?)

  record.errors.add(attribute, message, options) unless value.to_s.match regexp(record)
end