Skip to content

Commit

Permalink
Add support for namespaced validators
Browse files Browse the repository at this point in the history
Includes test and documentation for new feature

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
  • Loading branch information
samuelkadolph authored and spastorino committed Dec 11, 2010
1 parent 3074439 commit 2650742
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
8 changes: 7 additions & 1 deletion activemodel/lib/active_model/validations/validates.rb
Expand Up @@ -55,6 +55,10 @@ module ClassMethods
# validates :name, :title => true
# end
#
# Additionally validator classes may be in another namespace and still used within any class.
#
# validates :name, :'file/title' => true
#
# The validators hash can also handle regular expressions, ranges,
# arrays and strings in shortcut form, e.g.
#
Expand Down Expand Up @@ -86,8 +90,10 @@ def validates(*attributes)
defaults.merge!(:attributes => attributes)

validations.each do |key, options|
key = "#{key.to_s.camelize}Validator"

begin
validator = const_get("#{key.to_s.camelize}Validator")
validator = key.include?('::') ? key.constantize : const_get(key)
rescue NameError
raise ArgumentError, "Unknown validator: '#{key}'"
end
Expand Down
8 changes: 8 additions & 0 deletions activemodel/test/cases/validations/validates_test.rb
Expand Up @@ -3,6 +3,7 @@
require 'models/person'
require 'models/person_with_validator'
require 'validators/email_validator'
require 'validators/namespace/email_validator'

class ValidatesTest < ActiveModel::TestCase
setup :reset_callbacks
Expand Down Expand Up @@ -34,6 +35,13 @@ def test_validates_with_validator_class
assert_equal ['is not an email'], person.errors[:karma]
end

def test_validates_with_namespaced_validator_class
Person.validates :karma, :'namespace/email' => true
person = Person.new
person.valid?
assert_equal ['is not an email'], person.errors[:karma]
end

def test_validates_with_if_as_local_conditions
Person.validates :karma, :presence => true, :email => { :unless => :condition_is_true }
person = Person.new
Expand Down
6 changes: 6 additions & 0 deletions activemodel/test/validators/namespace/email_validator.rb
@@ -0,0 +1,6 @@
require 'validators/email_validator'

module Namespace
class EmailValidator < ::EmailValidator
end
end

0 comments on commit 2650742

Please sign in to comment.