Skip to content
Browse files

Be able to pass a validator method to #validates

  • Loading branch information...
1 parent ed7614a commit e9e9ed6b60a42a7c3afe3c4a9f8cf6d1e5422e59 @carllerche carllerche committed
View
6 activemodel/lib/active_model/validations/with.rb
@@ -8,6 +8,12 @@ def _merge_attributes(attr_names)
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.
View
12 activemodel/test/cases/validations/with_validation_test.rb
@@ -171,4 +171,16 @@ def check_validity!
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
View
4 activemodel/test/models/topic.rb
@@ -29,4 +29,8 @@ def perform_after_validation
self.after_validation_performed = true
end
+ def my_validation
+ errors.add :title, "is missing" unless title
+ end
+
end

0 comments on commit e9e9ed6

Please sign in to comment.
Something went wrong with that request. Please try again.