Created
April 11, 2017 22:43
-
-
Save barelyknown/73e9916bbe4c3a2356bf20c26191e5ed to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ComparisonValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
return if options[:allow_blank] && value.blank? | |
return if options[:allow_nil] && value.nil? | |
unless comparison_attribute = options[:attribute] | |
raise ArgumentError, "missing attribute option" | |
end | |
unless operator = options[:operator] | |
raise ArgumentError, "missing operator option" | |
end | |
comparison_value = record.public_send(comparison_attribute) | |
unless value && comparison_value && value.public_send(operator, comparison_value) | |
record.errors.add attribute, "must be #{operator} to #{comparison_attribute}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment