mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Optionally pass in the attribute being validated to an instance method validator
This commit is contained in:
parent
e9e9ed6b60
commit
cd13fbd8d8
3 changed files with 20 additions and 1 deletions
|
@ -10,7 +10,13 @@ module ActiveModel
|
||||||
|
|
||||||
class WithValidator < EachValidator
|
class WithValidator < EachValidator
|
||||||
def validate_each(record, attr, val)
|
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
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
@ -183,4 +183,13 @@ class ValidatesWithTest < ActiveModel::TestCase
|
||||||
assert !topic.valid?
|
assert !topic.valid?
|
||||||
assert_equal ['is missing'], topic.errors[:title]
|
assert_equal ['is missing'], topic.errors[:title]
|
||||||
end
|
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
|
end
|
||||||
|
|
|
@ -33,4 +33,8 @@ class Topic
|
||||||
errors.add :title, "is missing" unless title
|
errors.add :title, "is missing" unless title
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def my_validation_with_arg(attr)
|
||||||
|
errors.add attr, "is missing" unless send(attr)
|
||||||
|
end
|
||||||
|
|
||||||
end
|
end
|
||||||
|
|
Loading…
Reference in a new issue