Class: TimeFormatValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- TimeFormatValidator
- Defined in:
- lib/active_model_validators_ex/time_format_validator.rb
Instance Method Summary collapse
- #calculate_previous_time(record) ⇒ Object
-
#initialize(options) ⇒ TimeFormatValidator
constructor
A new instance of TimeFormatValidator.
- #validate_each(record, attribute, value) ⇒ Object
Constructor Details
#initialize(options) ⇒ TimeFormatValidator
Returns a new instance of TimeFormatValidator.
2 3 4 5 6 7 8 9 10 11 12 13 |
# File 'lib/active_model_validators_ex/time_format_validator.rb', line 2 def initialize() unless [:after].is_a?(NilClass) or [:after].is_a?(Proc) or [:after].is_a?(Time) raise ArgumentError, 'value after must be either NilClass, Proc or Time' end [:allow_nil] ||= false super() end |
Instance Method Details
#calculate_previous_time(record) ⇒ Object
32 33 34 35 36 37 38 39 |
# File 'lib/active_model_validators_ex/time_format_validator.rb', line 32 def calculate_previous_time(record) case [:after].class.name when 'Proc' [:after].call(record) when 'Time' [:after] end end |
#validate_each(record, attribute, value) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/active_model_validators_ex/time_format_validator.rb', line 15 def validate_each(record, attribute, value) return if [:allow_nil] && value.nil? parsed_time = value.is_a?(Time) ? value : Time.parse(value.to_s) previous_time = calculate_previous_time(record) if !previous_time.nil? and parsed_time < previous_time [:value] = value [:previous_time] = previous_time record.errors.add(attribute, :time_greater_than, ) end rescue StandardError => e record.errors.add(attribute, :time_invalid, ) end |