post icon

Display different styles for flash messages in Ruby on Rails

I saw this in a Rails video on Bala Paranj’s website http://rubyplus.org and thought is was a pretty cool way to display different flash messages throughout your app.

<% flash.each do |key, value| -%>
? <div id="notice_<%= key %>"><%= value %></div>
 <% end -%>

Then you can do different flash objects like this:

flash[:success] = "message here"
flash[:error] = "message here"

Then just style the messages with some css and you’ve got a notice div displaying error and success messages with less effort!

3 Comments

Leave a comment
  1. nuks
    23. Sep, 2009 at 1:34 am #

    I wrote a plugin partly similar to this.:-)
    http://nuks88.wordpress.com/2009/09/17/ymlized-and-styled-flash-messages-ysfm-in-rails/

  2. Darren
    23. Sep, 2009 at 10:50 am #

    @nuks Seems a little overkill for flash messages to me, but that’s just an opinion of someone who hasn’t done any work with a ton of different flash objects throughout his app. Managing the messages in the yml could be a little annoying as well, although your not repeating yourself, which is always good. ;) Thanks for the link and other option.

  3. nuks
    23. Sep, 2009 at 6:30 pm #

    Thanks Darren:-) We indeed have considerable amount of flash messages of some sorts in one of the app we developed. And at one point in our development time we were tasked to consolidate the messages for our client will change and may change them again. And then we consolidate our messages in one file. In this app I am saying we used xml but for the plugin I created I used yml. More rails way than xml.:D