DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

How To Handle Multiple Flash Keys

  • submit to reddit
        posted by Scott Raymond on rails list

I generally like to add something like this to my application_helper.rb:

def flash_div *keys
  keys.collect { |key| content_tag(:div, flash[key],
                                   :class => "flash #{key}") if flash[key] }.join

...and then this in my layouts/application.rhtml:

<%= flash_div :warning, :notice %>

Now, if my controller puts anything into flash[:warning] or flash[:notice],
they'll render like:

<div class="flash warning">Warning here</div>
<div class="flash notice">Notice here</div>

Nice and DRY, and easy to style. If I ever need some other flash key besides :warning or :notice, I can just add an argument to the flash_div call and I'm set.