From 73776cddfafa4bb6fb3f3a422af6f5b9e9982dfa Mon Sep 17 00:00:00 2001 From: Kieran Pilkington Date: Fri, 27 Nov 2009 14:26:38 +1300 Subject: [PATCH] Adding Proc support to validation messages so things like I18n and Time.now can be used in them. --- activerecord/lib/active_record/validations.rb | 2 ++ activerecord/test/cases/validations_test.rb | 8 ++++++++ 2 files changed, 10 insertions(+), 0 deletions(-) diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index 568e530..34f2cf9 100644 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -156,10 +156,12 @@ module ActiveRecord # error can be added to the same +attribute+ in which case an array will be returned on a call to on(attribute). # If no +messsage+ is supplied, :invalid is assumed. # If +message+ is a Symbol, it will be translated, using the appropriate scope (see translate_error). + # If +options[:message]+ is a Proc, it will be called, allowing for things like Time.now to be used within an error # def add(attribute, message = nil, options = {}) options[:message] = options.delete(:default) if options.has_key?(:default) error, message = message, nil if message.is_a?(Error) + options[:message] = options[:message].call if options[:message].is_a?(Proc) @errors[attribute.to_s] ||= [] @errors[attribute.to_s] << (error || Error.new(@base, attribute, message, options)) diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb index 00d915d..6c82013 100644 --- a/activerecord/test/cases/validations_test.rb +++ b/activerecord/test/cases/validations_test.rb @@ -1500,6 +1500,14 @@ class ValidationsTest < ActiveRecord::TestCase t.author_name = "Hubert J. Farnsworth" assert t.valid?, "A topic with an important title and author should be valid" end + + def test_validation_with_message_as_proc + Topic.validates_presence_of(:title, :message => proc { (2 + 2).to_s }) + + t = Topic.new + assert !t.valid? + assert_equal '4', t.errors.on(:title) + end end -- 1.6.5