Forum: Ruby on Rails Overloading error_message_on method in ActiveRecordHelper

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.
Martin Solli (Guest)
on 2005-12-23 14:52
(Received via mailing list)
Hello all

I would like to overload the error_message_on method in the
ActiveRecordHelper module in order to emit a span tag instead of a div
tag. I try to achieve this by way of plugins: Under vendor/plugins
I've made a error_messages_on_fix directory, containing init.rb like
this:
---
require 'active_record_helper_fix'
---

..and a lib directory with active_record_helper_fix.rb like this:
---
require 'action_view/helpers/active_record_helper'

module ActionView
  module Helpers
    module ActiveRecordHelper
      def error_message_on(object, method, prepend_text = "",
append_text = "", css_class = "formError", span = false)
        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
---

My plan is to be able to use this method with a call like this:
error_message_on('user', 'last_name', :span => true)

This results in my application coming tumbling down with this error:
---
 Showing app/views/user/_form.rhtml where line #3 raised:
stack level too deep
Extracted source (around line #3):
1: <div class="user_first_name">
2: <p><label for="user_first_name">Fornavn</label><br />
3: <%= text_field('user', 'first_name', 'size' => 25) %>
4: <%= error_message_on('user', 'first_name') %></p>
5: </div>
---

I feel that the problem may be my lack of understanding of how modules
work in Ruby. Or I'm trying to do something simple in a hard way. I
don't know. I would appreciate some tips on how to achieve this.

-martin
David L. (Guest)
on 2005-12-23 16:43
(Received via mailing list)
I'm trying to do something quite similar myself for the first time.

i'll offer one piece of advice: putting that code in a file that also
contains a model or helper means you don't have to restart the server
to see your changes, which makes debugging the thing a lot easier
(thats not a deployment strategy mind you).

If you leave the body of your method the same as AR's default does it
still throw the 'stack too deep' ?

cheers,
David
This topic is locked and can not be replied to.