From 2466f653237305e1ecd255e61460c234fa8f4b41 Mon Sep 17 00:00:00 2001 From: Samuel Elliott Date: Sun, 17 Jan 2010 12:15:52 +0100 Subject: [PATCH] Adding Proc support to validation messages so that they can become a little more dynamic, allowing for customisations during the request. --- activemodel/lib/active_model/errors.rb | 2 ++ activemodel/test/cases/validations_test.rb | 8 ++++++++ 2 files changed, 10 insertions(+), 0 deletions(-) diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb index 0b6c75c..2e5bcab 100644 --- a/activemodel/lib/active_model/errors.rb +++ b/activemodel/lib/active_model/errors.rb @@ -60,9 +60,11 @@ module ActiveModel # 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 +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 = {}) message ||= :invalid message = generate_message(attribute, message, options) if message.is_a?(Symbol) + message = message.call if message.is_a?(Proc) self[attribute] << message end diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb index 38a2a71..bd94dcd 100644 --- a/activemodel/test/cases/validations_test.rb +++ b/activemodel/test/cases/validations_test.rb @@ -212,4 +212,12 @@ class ValidationsTest < ActiveModel::TestCase all_errors = t.errors.to_a assert_deprecated { assert_equal all_errors, t.errors.each_full{|err| err} } 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 t.errors[:title].include?('4') + end end -- 1.6.3.3