Class: TimeFormatValidator

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

Instance Method Summary collapse

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(options)
  unless options[:after].is_a?(NilClass) or
         options[:after].is_a?(Proc)     or
         options[:after].is_a?(Time)
    raise ArgumentError,
          'value after must be either NilClass, Proc or Time'
  end

  options[:allow_nil] ||= false

  super(options)
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 options[:after].class.name
  when 'Proc'
    options[:after].call(record)
  when 'Time'
    options[: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 options[: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
    options[:value]         = value
    options[:previous_time] = previous_time

    record.errors.add(attribute, :time_greater_than, options)
  end
rescue StandardError => e
  record.errors.add(attribute, :time_invalid, options)
end