From 47a5fd4c4ba447c997c0a029adfa80d8b790b25a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 7 Jan 2010 19:22:32 +0100 Subject: Allow :if, :unless, :on, :allow_nil and :allow_blank as shared options in validates. --- activemodel/lib/active_model/validations.rb | 4 +--- .../lib/active_model/validations/validates.rb | 24 ++++++++++++++++------ 2 files changed, 19 insertions(+), 9 deletions(-) (limited to 'activemodel/lib') diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb index 573c914e63..276472ea46 100644 --- a/activemodel/lib/active_model/validations.rb +++ b/activemodel/lib/active_model/validations.rb @@ -121,9 +121,7 @@ module ActiveModel # end # end # - def read_attribute_for_validation(key) - send(key) - end + alias :read_attribute_for_validation :send end end diff --git a/activemodel/lib/active_model/validations/validates.rb b/activemodel/lib/active_model/validations/validates.rb index e8935d3794..61caf32c06 100644 --- a/activemodel/lib/active_model/validations/validates.rb +++ b/activemodel/lib/active_model/validations/validates.rb @@ -31,7 +31,7 @@ module ActiveModel # attr_accessor :name, :email # # validates :name, :presence => true, :uniqueness => true, :length => { :maximum => 100 } - # validates :email, :presence => true, :email => true + # validates :email, :presence => true, :format => { :with => /@/ } # end # # Validator classes my also exist within the class being validated @@ -44,21 +44,33 @@ module ActiveModel # end # end # end - # + # # class Film # include ActiveModel::Validations # include MyValidators # # validates :name, :title => true # end - # + # + # The options :if, :unless, :on, :allow_blank and :allow_nil can be given to one specific + # validator: + # + # 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) - validations = attributes.extract_options! + defaults = attributes.extract_options! + validations = defaults.slice!(:if, :unless, :on, :allow_blank, :allow_nil) 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| begin validator = const_get("#{key.to_s.camelize}Validator") @@ -66,7 +78,7 @@ module ActiveModel raise ArgumentError, "Unknown validator: '#{key}'" end - validates_with(validator, (options == true ? {} : options).merge(:attributes => attributes)) + validates_with(validator, defaults.merge(options == true ? {} : options)) end end end -- cgit v1.2.3