Last active
August 29, 2015 14:06
-
-
Save msievers/5796ab5854ee0e839034 to your computer and use it in GitHub Desktop.
Seamlessly integrated custom rails validator
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
de: | |
activemodel: | |
errors: | |
messages: | |
distinctness: "müssen unterschiedlich sein" |
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
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 |
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 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