Permalink
Browse files

Adding Proc support to validation messages so that they can become a …

…little more dynamic, allowing for customisations during the request [#3514 status:resolved].

Signed-off-by: José Valim <jose.valim@gmail.com>
  • Loading branch information...
1 parent c0d31ca commit 31ea83eb898786f853bd7ce7075986fa120f949d @lenary lenary committed with josevalim Jan 17, 2010
Showing with 10 additions and 0 deletions.
  1. +2 −0 activemodel/lib/active_model/errors.rb
  2. +8 −0 activemodel/test/cases/validations_test.rb
@@ -60,9 +60,11 @@ def to_xml(options={})
# error can be added to the same +attribute+ in which case an array will be returned on a call to <tt>on(attribute)</tt>.
# 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
@@ -212,4 +212,12 @@ def test_deprecated_errors_on_base_and_each
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 { "no blanks here".upcase })
+
+ t = Topic.new
+ assert !t.valid?
+ assert ["NO BLANKS HERE"], t.errors[:title]
+ end
end

2 comments on commit 31ea83e

Surprised I didn't get mentioned somewhere for the initial implementation/patch...

https://rails.lighthouseapp.com/projects/8994/tickets/3514-adding-proc-support-on-validation-messages

Aren't authors supposed to base patches on the existing ones... or committers verify it's the authors sole work?

Seems like I missed out on a very helpful commit! :-(

Contributor

lenary replied Feb 8, 2010

Sorry for not mentioning you, I probably should have added something to the message.

I believe the usual workflow should be making a patch for master and backporting, but i can't remember where i saw this.

Your patch should still be applied to the 2-3-master branch, as this patch is only it forward-ported.

Please sign in to comment.