Skip to content

Instantly share code, notes, and snippets.

@albaer
Created November 15, 2016 04:18
Show Gist options
  • Save albaer/816dc6c35a5bd4bfc5106abd33baa394 to your computer and use it in GitHub Desktop.
Save albaer/816dc6c35a5bd4bfc5106abd33baa394 to your computer and use it in GitHub Desktop.
class DateTimeValidator < ActiveModel::EachValidator
CHECKS = {
after: :>,
before: :<,
after_or_equal_to: :>=,
before_or_equal_to: :<=
}
def check_validity!
keys = CHECKS.keys
options.slice(*keys).each do |option, value|
unless value.is_a?(Symbol) || value.is_a?(Time)
raise ArgumentError, ":#{option} must be a Symbol or a valid Time"
end
end
end
def validate_each(record, attr_name, value)
return if options[:allow_nil] && value.nil?
options.slice(*CHECKS.keys).each do |option, option_value|
case option_value
when Symbol
option_value = record.send(option_value)
when Time
option_value = option_value
end
unless value.send(CHECKS[option], option_value)
record.errors[attr_name] << "must be #{option.to_s.humanize.downcase} #{option_value}"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment