aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-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