Rails Flash Notices with Fade

November 11th, 2008 by admin Leave a reply »

Something I normally find in the view code – I’ve written a snippet that takes care of in the application helper.  The method handles a flash with multiple messages in it (I don’t know when/how that’d ever come about – but if it did it’ll handle it just find displaying both messages).


def show_flash_message(options={})
  html = content_tag(:div, flash.collect{ |key,msg| content_tag(:div, msg, :class => key) },
:id => 'flash-message')
  if options.key?(:fade)
    html << content_tag(:script,"setTimeout("new Effect.Fade('flash-message');",#{options[:fade]*1000})",
:type => 'text/javascript')
  end
  html
end

Then in your view simply refer to:

     <%= show_flash_message(:fade => 4) %>

If you want the fade option be sure to have the javascript_include_tag :defaults on your page – the fade effect uses prototype.

Enjoy.

Advertisement

Leave a Reply