From e9e9ed6b60a42a7c3afe3c4a9f8cf6d1e5422e59 Mon Sep 17 00:00:00 2001 From: Carl Lerche Date: Sat, 5 Feb 2011 16:33:00 -0800 Subject: [PATCH] Be able to pass a validator method to #validates --- activemodel/lib/active_model/validations/with.rb | 6 ++++++ .../test/cases/validations/with_validation_test.rb | 12 ++++++++++++ activemodel/test/models/topic.rb | 4 ++++ 3 files changed, 22 insertions(+) diff --git a/activemodel/lib/active_model/validations/with.rb b/activemodel/lib/active_model/validations/with.rb index 200efd4eb5..16d81263a2 100644 --- a/activemodel/lib/active_model/validations/with.rb +++ b/activemodel/lib/active_model/validations/with.rb @@ -8,6 +8,12 @@ module ActiveModel end end + class WithValidator < EachValidator + def validate_each(record, attr, val) + record.send options[:with] + end + end + module ClassMethods # Passes the record off to the class or classes specified and allows them # to add errors based on more complex conditions. diff --git a/activemodel/test/cases/validations/with_validation_test.rb b/activemodel/test/cases/validations/with_validation_test.rb index 6d825cd316..33efedcd7c 100644 --- a/activemodel/test/cases/validations/with_validation_test.rb +++ b/activemodel/test/cases/validations/with_validation_test.rb @@ -171,4 +171,16 @@ class ValidatesWithTest < ActiveModel::TestCase assert topic.errors[:title].empty? assert topic.errors[:content].empty? end + + test "validates_with can validate with an instance method" do + Topic.validates :title, :with => :my_validation + + topic = Topic.new :title => "foo" + assert topic.valid? + assert topic.errors[:title].empty? + + topic = Topic.new + assert !topic.valid? + assert_equal ['is missing'], topic.errors[:title] + end end diff --git a/activemodel/test/models/topic.rb b/activemodel/test/models/topic.rb index 2f0bb95071..8d49c1dd27 100644 --- a/activemodel/test/models/topic.rb +++ b/activemodel/test/models/topic.rb @@ -29,4 +29,8 @@ class Topic self.after_validation_performed = true end + def my_validation + errors.add :title, "is missing" unless title + end + end