Helper to Display Rails Flash Messages

by Ian Purton

A simple code snippet for displaying your flash[:warning] = "Warning Message" messages in rails.

Add the following to your application_helper.rb.

To show all messages place this code in your view (rhtml).

Also here’s some CSS to style the messages.

  • nuks
    Perhaps you guys may want to look at this -> http://nuks88.wordpress.com/2009/09/17/ymlized-...
  • OK, let me repeat that… Do you have a sense of wonder about my comfortable doubt A JOKE! ) What is three feet long? A yard.
  • @Dallas

    I disagree... I think having a little markup in your helpers is perfectly acceptable. They are "help" for your presentation after all. I think the main mistake people make is using helpers for things that should go into a partial.
  • woops, I mean

    def flash_helper
    [:notice, :warning, :message].map { |f| content_tag(:div, flash[f], :class => f) if flash[f] }
    end
  • here's another version of the above, even more terse...

    def flash_helper
    [:notice, :warning, :message].map { |f| content_tag(:div, flash[f], :class => type) if flash[f] }
    end
  • Formatting of previous comment (or lackthereof) may cause misunderstanding. Code should read:


    def render_flash_messages
    result = ''
    for type in [:notice, :warning, :message]
    message = flash[type]
    result #{message}”
    end
    result
    end


    I should also note that content_tag is quite slow, which is why I used the inline string to generate HTML. If a partial was used instead (for the MVC purist, which I am usually) that would have incurred an even higher performance hit, which in most of my applications isn't worth the extra purity of the code.
  • I use a more terse version of what your code does:


    def render_flash_messages
    result = ''
    for type in [:notice, :warning, :message]
    message = flash[type]
    # commented out content_tag, while cleaner is very inefficient
    #content_tag('div', message, :class => type) if message
    # using string inline method...
    result #{message}"
    end
    result
    end


    A few things should be noted:
    flash_helper and render_flash_messages are roughly equivalent performance wiseflash_helper has a defect in it. Line 8 should read: fl = fl + ”#{flash[name]}”
  • Dallas
    You really should not put xhtml code into your helpers. Keep your content, layout, functional code, and styles separate.
  • Thank You
blog comments powered by Disqus