lib/active_model/validations/validates.rb in activemodel-3.0.20 vs lib/active_model/validations/validates.rb in activemodel-3.1.0.beta1
- old
+ new
@@ -53,59 +53,73 @@
# end
#
# validates :name, :title => true
# end
#
- # The validators hash can also handle regular expressions, ranges and arrays:
+ # 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.
+ #
# validates :email, :format => /@/
# validates :gender, :inclusion => %w(male female)
# validates :password, :length => 6..20
#
- # Finally, the options :if, :unless, :on, :allow_blank and :allow_nil can be given
- # to one specific validator:
+ # When using shortcut form, ranges and arrays are passed to your
+ # validator's initializer as +options[:in]+ while other types including
+ # regular expressions and strings are passed as +options[:with]+
#
+ # Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+ and +:allow_nil+ can be given
+ # to one specific validator, as a hash:
+ #
# validates :password, :presence => { :if => :password_required? }, :confirmation => true
#
# Or to all at the same time:
#
# validates :password, :presence => true, :confirmation => true, :if => :password_required?
#
def validates(*attributes)
defaults = attributes.extract_options!
- validations = defaults.slice!(:if, :unless, :on, :allow_blank, :allow_nil)
+ validations = defaults.slice!(*_validates_default_keys)
raise ArgumentError, "You need to supply at least one attribute" if attributes.empty?
- raise ArgumentError, "Attribute names must be symbols" if attributes.any?{ |attribute| !attribute.is_a?(Symbol) }
raise ArgumentError, "You need to supply at least one validation" if validations.empty?
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
validates_with(validator, defaults.merge(_parse_validates_options(options)))
end
end
protected
+ # When creating custom validators, it might be useful to be able to specify
+ # additional default keys. This can be done by overwriting this method.
+ def _validates_default_keys
+ [ :if, :unless, :on, :allow_blank, :allow_nil ]
+ end
+
def _parse_validates_options(options) #:nodoc:
case options
when TrueClass
{}
when Hash
options
- when Regexp
- { :with => options }
when Range, Array
{ :in => options }
else
- raise ArgumentError, "#{options.inspect} is an invalid option. Expecting true, Hash, Regexp, Range, or Array"
+ { :with => options }
end
end
end
end
end