Forum: Ruby on Rails Re: RESOLVED: Overloading error_message_on method in ActiveR

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bc71b30fc8d140d7b4027138e8f62c33?d=identicon&s=25 Martin Solli (Guest)
on 2005-12-27 13:38
(Received via mailing list)
Leaving the body of the method the same as the default still throws
the "stack level too deep" error.  As a matter of fact, it only
disappears if I comment out the 'require' in line 1.

As it turned out, it was the method definiton itself that caused
problems. Ruby doesn't have keyword arguments, but I tried calling the
method as if it had. But when I changed the definiton to one with a
hash that simulates keywords, it works just fine:

---
module ActionView
  module Helpers
    module ActiveRecordHelper
      def error_message_on(object, method, params = nil)
        if params.class == Hash
          prepend_text = params[:prepend_text] || ""
          append_text  = params[:append_text]  || ""
          css_class    = params[:css_class]    || "formError"
          span         = params[:span]         || false
        end
        if errors =
instance_variable_get("@#{object}").errors.on(method)
          content_tag(span ? "span" : "div",
"#{prepend_text}#{errors.is_a?(Array) ? errors.first :
errors}#{append_text}", :class => css_class)
        end
      end
    end
  end
end
---

I don't know if this is the proper way to do it, but it seems to work.
Now I can use
<%= error_message_on('user', 'first_name', :span => true) %>
in my templates when I want my error messages in a <span> instead of in
a <div>.

-martin
This topic is locked and can not be replied to.