Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Better shortcut options for custom validators [#5672 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
  • Loading branch information...
commit 275f922a23b780600a32f70de5b661371c8ffdf4 1 parent 097240f
@obie obie authored josevalim committed
View
15 activemodel/lib/active_model/validations/validates.rb
@@ -55,14 +55,19 @@ module ClassMethods
# validates :name, :title => true
# end
#
- # The validators hash can also handle regular expressions, ranges and arrays:
+ # 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
#
@@ -99,10 +104,10 @@ def _parse_validates_options(options) #:nodoc:
{}
when Hash
options
- when Regexp
- { :with => options }
when Range, Array
{ :in => options }
+ else
+ { :with => options }
end
end
end
View
9 activemodel/test/cases/validations/validates_test.rb
@@ -111,4 +111,13 @@ def test_validates_with_included_validator_and_options
person.valid?
assert_equal ['Local validator please'], person.errors[:title]
end
+
+ def test_validates_with_included_validator_and_wildcard_shortcut
+ # Shortcut for PersonWithValidator.validates :title, :like => { :with => "Mr." }
+ PersonWithValidator.validates :title, :like => "Mr."
+ person = PersonWithValidator.new
+ person.title = "Ms. Pacman"
+ person.valid?
+ assert_equal ['does not appear to be like Mr.'], person.errors[:title]
+ end
end
View
13 activemodel/test/models/person_with_validator.rb
@@ -7,5 +7,18 @@ def validate_each(record, attribute, value)
end
end
+ class LikeValidator < ActiveModel::EachValidator
+ def initialize(options)
+ @with = options[:with]
+ super
+ end
+
+ def validate_each(record, attribute, value)
+ unless value[@with]
+ record.errors.add attribute, "does not appear to be like #{@with}"
+ end
+ end
+ end
+
attr_accessor :title, :karma
end
Please sign in to comment.
Something went wrong with that request. Please try again.