Skip to content
Browse files

Find all validators for multiple attributes

  • Loading branch information...
1 parent cd13fbd commit cf9324e5909e71ec0a2477338e696b6af2f17f13 @carllerche carllerche committed Feb 5, 2011
Showing with 22 additions and 2 deletions.
  1. +4 −2 activemodel/lib/active_model/validations.rb
  2. +18 −0 activemodel/test/cases/validations_test.rb
View
6 activemodel/lib/active_model/validations.rb
@@ -146,8 +146,10 @@ def validators
end
# List all validators that being used to validate a specific attribute.
- def validators_on(attribute)
- _validators[attribute.to_sym]
+ def validators_on(*attributes)
+ attributes.inject([]) do |all, attribute|
+ all |= _validators[attribute.to_sym] || []
+ end
end
# Check if method is an attribute method or not.
View
18 activemodel/test/cases/validations_test.rb
@@ -254,6 +254,24 @@ def test_accessing_instance_of_validator_on_an_attribute
assert_equal 10, Topic.validators_on(:title).first.options[:minimum]
end
+ def test_list_of_validators_on_multiple_attributes
+ Topic.validates :title, :length => { :minimum => 10 }
+ Topic.validates :author_name, :presence => true, :format => /a/
+
+ validators = Topic.validators_on(:title, :author_name)
+
+ assert_equal [
+ ActiveModel::Validations::FormatValidator,
+ ActiveModel::Validations::LengthValidator,
+ ActiveModel::Validations::PresenceValidator
+ ], validators.map { |v| v.class }.sort_by { |c| c.to_s }
+ end
+
+ def test_list_of_validators_will_be_empty_when_empty
+ Topic.validates :title, :length => { :minimum => 10 }
+ assert_equal [], Topic.validators_on(:author_name)
+ end
+
def test_validations_on_the_instance_level
auto = Automobile.new

0 comments on commit cf9324e

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