Class: AgeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/age_validator.rb

Instance Method Summary collapse

Constructor Details

#initialize(age_service: AgeService, **args) ⇒ AgeValidator


2
3
4
5
# File 'app/validators/age_validator.rb', line 2

def initialize(age_service: AgeService, **args)
  self.age_service = age_service
  super(args)
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object


7
8
9
10
11
12
13
14
# File 'app/validators/age_validator.rb', line 7

def validate_each(record, attribute, value)
  return if value.nil? || value.blank?
  age = age_service.call(date_of_birth: value)
  if options.key?(:greater_than_or_equal_to)
    gte = options[:greater_than_or_equal_to]
    record.errors.add(attribute, :age_less_than, count: gte) unless age >= gte
  end
end