From cfd421daa2b04216e27d666361eb4053020e027d Mon Sep 17 00:00:00 2001 From: James Hill Date: Wed, 5 Aug 2009 11:44:44 -0500 Subject: Allow validations to use values from custom readers [#2936 state:resolved] Signed-off-by: Joshua Peek --- activemodel/lib/active_model/validations.rb | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) (limited to 'activemodel/lib/active_model/validations.rb') diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb index 54a869396d..0fca96e5cc 100644 --- a/activemodel/lib/active_model/validations.rb +++ b/activemodel/lib/active_model/validations.rb @@ -66,7 +66,7 @@ module ActiveModel # Declare the validation. send(validation_method(options[:on]), options) do |record| attrs.each do |attr| - value = record.send(attr) + value = record.instance_eval { read_attribute_for_validation(attr) } next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank]) yield record, attr, value end @@ -95,6 +95,28 @@ module ActiveModel def invalid? !valid? end + + protected + # Hook method defining how an attribute value should be retieved. By default this is assumed + # to be an instance named after the attribute. Override this method in subclasses should you + # need to retrieve the value for a given attribute differently e.g. + # class MyClass + # include ActiveModel::Validations + # + # def initialize(data = {}) + # @data = data + # end + # + # private + # + # def read_attribute_for_validation(key) + # @data[key] + # end + # end + # + def read_attribute_for_validation(key) + send(key) + end end end -- cgit v1.2.3 From 5ce3831faf684aea75948ce4602b6b9de361c11e Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Thu, 6 Aug 2009 00:11:28 +0100 Subject: Use send instead of instance_eval --- activemodel/lib/active_model/validations.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activemodel/lib/active_model/validations.rb') diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb index 0fca96e5cc..7d49e60790 100644 --- a/activemodel/lib/active_model/validations.rb +++ b/activemodel/lib/active_model/validations.rb @@ -66,7 +66,7 @@ module ActiveModel # Declare the validation. send(validation_method(options[:on]), options) do |record| attrs.each do |attr| - value = record.instance_eval { read_attribute_for_validation(attr) } + value = record.send(:read_attribute_for_validation, attr) next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank]) yield record, attr, value end -- cgit v1.2.3