Rails and Stuff at Abel killed Cain

Ruby on Rails and other Webdevelopment

Ruby on Rails provides a nice way to display error_messages; just by adding form.error_messages you get a nice overview of all your errors.

But i prefer to have it in different ways, so i 1) dont want the on_error_message-output to be a div element, 2) further i want to give each input field having bad content to be marked – by adding an error-class to that specific element for example.

Since i had to figure it out, here are the results for changing both.

1) different element instead of a div at on_error_message?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
module SpanOnErrorMessages  #rename it properly
        # File actionpack/lib/action_view/helpers/active_record_helper.rb, line 109
    def error_message_on(object, method, *args)
        options = args.extract_options!
        unless args.empty?
            ActiveSupport::Deprecation.warn('error_message_on takes an option hash instead of separate ' +
            'prepend_text, append_text, and css_class arguments', caller)
           
            options[:prepend_text] = args[0] || ''
            options[:append_text] = args[1] || ''
            options[:css_class] = args[2] || 'formError'
        end
        options.reverse_merge!(:prepend_text => '', :append_text => '', :css_class => 'formError')
       
        if (obj = (object.respond_to?(:errors) ? object : instance_variable_get("@#{object}"))) && (errors = obj.errors.on(method))
            content_tag("span",  #rewritten to span! hooray!
            "#{options[:prepend_text]}#{ERB::Util.html_escape(errors.is_a?(Array) ? errors.first : errors)}#{options[:append_text]}",
            :class => options[:css_class]
            )
        else
          ''
        end
    end
end      

#now telling ActionView to use it!
ActionView::Base.send :include, SpanOnErrorMessages

there we go, thats it! have fun!

If you need, set the element as a hash-paramter to have this more dynamic.

Okay now thats pretty! how about having:
2) adding an error-class to the bad input elements:

1
2
3
4
5
6
7
8
9
10
11
12
#environment.rb
ActionView::Base.field_error_proc = Proc.new do |html_tag, instace_tag|
    error_class = "error"
    if html_tag =~ /<(input|textarea|select)[^>]+class=/
        style_attribute = html_tag =~ /class=['"]/   #'my wordpress colors wierd
        html_tag.insert(style_attribute + 7, "#{error_class} ")
    elsif html_tag =~ /<(input|textarea|select)/
        first_whitespace = html_tag =~ /\s/
        html_tag[first_whitespace] = " class=\"#{error_class}\" "
    end
    html_tag
end

Thats fine! now a wrong input should look like:
<input class=”error” id=”user_email” … type=”text” value=”just@wrong”>

Hope you can take use of that? tell me! :)

Write a Comment