Class: AgeValidator

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

Constant Summary collapse

COMPARATORS =
{ :over => :>=, :under => :<= }.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.localesObject



17
18
19
# File 'lib/age_calculator/validator.rb', line 17

def self.locales
  Dir[Pathname.new(__FILE__).join('../../../config/locales/*.yml')]
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/age_calculator/validator.rb', line 4

def validate_each(record, attribute, value)
  return record.errors.add(attribute, :blank, options) if value.blank?
  return record.errors.add(attribute, :not_date, options) unless value.is_a?(Date)

  age = AgeCalculator.new(value).age(asof: options[:asof])

  options.slice(*COMPARATORS.keys).each do |option_key, option_value|
    unless age.send(COMPARATORS[option_key], option_value.to_i)
      record.errors.add(attribute, :"age_#{option_key}", options.merge(age: option_value))
    end
  end
end