Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@barelyknown
Created April 11, 2017 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barelyknown/73e9916bbe4c3a2356bf20c26191e5ed to your computer and use it in GitHub Desktop.
Save barelyknown/73e9916bbe4c3a2356bf20c26191e5ed to your computer and use it in GitHub Desktop.
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