aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel
diff options
context:
space:
mode:
authorCarl Lerche <me@carllerche.com>2011-02-05 16:44:35 -0800
committerCarl Lerche <me@carllerche.com>2011-02-05 16:44:35 -0800
commitcd13fbd8d8071b822f6d4f8967ef80c617c036ba (patch)
tree5f93f68a4f5ae6bf285fb3eb7604a647294d165d /activemodel
parente9e9ed6b60a42a7c3afe3c4a9f8cf6d1e5422e59 (diff)
downloadrails-cd13fbd8d8071b822f6d4f8967ef80c617c036ba.tar.gz
rails-cd13fbd8d8071b822f6d4f8967ef80c617c036ba.tar.bz2
rails-cd13fbd8d8071b822f6d4f8967ef80c617c036ba.zip
Optionally pass in the attribute being validated to an instance method validator
Diffstat (limited to 'activemodel')
-rw-r--r--activemodel/lib/active_model/validations/with.rb8
-rw-r--r--activemodel/test/cases/validations/with_validation_test.rb9
-rw-r--r--activemodel/test/models/topic.rb4
3 files changed, 20 insertions, 1 deletions
diff --git a/activemodel/lib/active_model/validations/with.rb b/activemodel/lib/active_model/validations/with.rb
index 16d81263a2..1663697727 100644
--- a/activemodel/lib/active_model/validations/with.rb
+++ b/activemodel/lib/active_model/validations/with.rb
@@ -10,7 +10,13 @@ module ActiveModel
class WithValidator < EachValidator
def validate_each(record, attr, val)
- record.send options[:with]
+ method_name = options[:with]
+
+ if record.method(method_name).arity == 0
+ record.send method_name
+ else
+ record.send method_name, attr
+ end
end
end
diff --git a/activemodel/test/cases/validations/with_validation_test.rb b/activemodel/test/cases/validations/with_validation_test.rb
index 33efedcd7c..07c1bd0533 100644
--- a/activemodel/test/cases/validations/with_validation_test.rb
+++ b/activemodel/test/cases/validations/with_validation_test.rb
@@ -183,4 +183,13 @@ class ValidatesWithTest < ActiveModel::TestCase
assert !topic.valid?
assert_equal ['is missing'], topic.errors[:title]
end
+
+ test "optionally pass in the attribute being validated when validating with an instance method" do
+ Topic.validates :title, :content, :with => :my_validation_with_arg
+
+ topic = Topic.new :title => "foo"
+ assert !topic.valid?
+ assert topic.errors[:title].empty?
+ assert_equal ['is missing'], topic.errors[:content]
+ end
end
diff --git a/activemodel/test/models/topic.rb b/activemodel/test/models/topic.rb
index 8d49c1dd27..c9af78f595 100644
--- a/activemodel/test/models/topic.rb
+++ b/activemodel/test/models/topic.rb
@@ -33,4 +33,8 @@ class Topic
errors.add :title, "is missing" unless title
end
+ def my_validation_with_arg(attr)
+ errors.add attr, "is missing" unless send(attr)
+ end
+
end