Skip to content

Instantly share code, notes, and snippets.

@msievers
Last active August 29, 2015 14:06
Show Gist options
  • Save msievers/5796ab5854ee0e839034 to your computer and use it in GitHub Desktop.
Save msievers/5796ab5854ee0e839034 to your computer and use it in GitHub Desktop.
Seamlessly integrated custom rails validator
de:
activemodel:
errors:
messages:
distinctness: "müssen unterschiedlich sein"
module DistinctnessValidator
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def validates_distinctness_of(*attr_names)
# from rails/activemodel/lib/active_model/validations/with.rb
options = attr_names.extract_options!.symbolize_keys
attr_names.flatten!
options[:attributes] = attr_names
# anonymous validator class
validator = Class.new(ActiveModel::EachValidator) do
def validate_each(record, attribute, value)
if value == record.send(options[:from])
record.errors.add(attribute, :distinctness, options)
record.errors.add(options[:from], :distinctness, options)
end
end
end
validates_with validator, options
end
end
end
class SomeModel
include ActiveModel::Model
include ActiveModel::Validations
include DistinctnessValidator
attr_accessor :current_password
attr_accessor :new_password
validates_presence_of :current_password
validates_presence_of :new_password
# ...
validates_distinctness_of :new_password, from: :current_password
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment