Optionally pass in the attribute being validated to an instance method validator

This commit is contained in:
Carl Lerche 2011-02-05 16:44:35 -08:00
parent e9e9ed6b60
commit cd13fbd8d8
3 changed files with 20 additions and 1 deletions

View File

@ -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

View File

@ -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

View File

@ -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