mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Be able to pass a validator method to #validates
This commit is contained in:
parent
ed7614aa7d
commit
e9e9ed6b60
3 changed files with 22 additions and 0 deletions
|
@ -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.
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -29,4 +29,8 @@ class Topic
|
|||
self.after_validation_performed = true
|
||||
end
|
||||
|
||||
def my_validation
|
||||
errors.add :title, "is missing" unless title
|
||||
end
|
||||
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue