Created
November 15, 2016 04:18
-
-
Save albaer/816dc6c35a5bd4bfc5106abd33baa394 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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