Sha256: 01efbdb1b041f37f3acc0cb123d79ead1c65b46950af28de99e01a63b9679a3e

Contents?: true

Size: 818 Bytes

Versions: 1

Compression:

Stored size: 818 Bytes

Contents

class TimeFormatValidator < ActiveModel::EachValidator
  def initialize(options)
    options[:allow_nil] ||= false

    super(options)
  end

  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
      record.errors[attribute] << "invalid value, #{value} must be after #{previous_time}"
    end
  rescue StandardError => e
    record.errors[attribute] << "invalid value, #{value} not valid for #{attribute}"
  end

  def calculate_previous_time(record)
    case options[:after].class.name
    when 'Proc'
      options[:after].call(record)
    when 'Time'
      options[:after]
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
active_model_validators_ex-0.3.1 lib/active_model_validators_ex/time_format_validator.rb