diff options
Diffstat (limited to 'activemodel/lib/active_model/validations/with.rb')
-rw-r--r-- | activemodel/lib/active_model/validations/with.rb | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/activemodel/lib/active_model/validations/with.rb b/activemodel/lib/active_model/validations/with.rb index 83d3ea80d6..2a2d0d55b4 100644 --- a/activemodel/lib/active_model/validations/with.rb +++ b/activemodel/lib/active_model/validations/with.rb @@ -75,5 +75,71 @@ module ActiveModel end end end + + # Passes the record off to the class or classes specified and allows them + # to add errors based on more complex conditions. + # + # class Person + # include ActiveModel::Validations + # + # validates :instance_validations + # + # def instance_validations + # validates_with MyValidator + # end + # end + # + # class MyValidator < ActiveModel::Validator + # def validate(record) + # if some_complex_logic + # record.errors[:base] << "This record is invalid" + # end + # end + # + # private + # def some_complex_logic + # # ... + # end + # end + # + # You may also pass it multiple classes, like so: + # + # class Person + # include ActiveModel::Validations + # + # validates :instance_validations, :on => :create + # + # def instance_validations + # validates_with MyValidator, MyOtherValidator + # end + # end + # + # Standard configuration options (:on, :if and :unless), which are + # available on the class version of validates_with, should instead be + # placed on the <tt>validates</tt> method as these are applied and tested + # in the callback + # + # If you pass any additional configuration options, they will be passed + # to the class and available as <tt>options</tt>: + # + # class Person + # include ActiveModel::Validations + # validates_with MyValidator, :my_custom_key => "my custom value" + # end + # + # class MyValidator < ActiveModel::Validator + # def validate(record) + # options[:my_custom_key] # => "my custom value" + # end + # end + # + def validates_with(*args, &block) + options = args.extract_options! + args.each do |klass| + validator = klass.new(options, &block) + validator.setup(self) if validator.respond_to?(:setup) + validator.validate(self) + end + end end end
\ No newline at end of file |