Class: TimeValidator

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

Overview

Checks the time is after|before|not after|not before given time.

validates :next_alarm, time: { after: Time.now, not_after: 1.day.from_now }

Use the :allow_nil key to skip validation in case the attribute value isn’t set.

validates :next_alarm, time: { after: Time.now, allow_nil: true }

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/validators/time_validator.rb', line 15

def validate_each(record, attribute, value)
  return if value.nil? && options[:allow_nil]
  { after: :>, before: :<, not_after: :<=, not_before: :>= }.each do |key, check|
    if target = options[key]
      record.errors.add attribute, :"#{ key }_time" unless value.try check, target
    end
  end
end