Sometimes our layout file can get cluttered with various flash messages. Each message takes three lines of code as we want to check that each message isn’t nil before trying to display it within a paragraph tag.
<html>
<!-- (head snipped) -->
<body>
<h1>ASCIIcasts</h1>
<% unless flash[:notice].nil? %>
<div id="notice"><%= flash[:notice] %></div>
<% end %>
<% unless flash[:notice].nil? %>
<div id="notice"><%= flash[:notice] %></div>
<% end %>
<%= yield %>
</body>
</html>
flash
messages in the layout file.
There is an easier way to do this which is to loop through the flash, and display each flash message that way. The code looks like this:
<% flash.each do |key,msg| %>
<%= content_tag :p, msg, :id => key %>
<% end %>
content_tag
takes three parameters: the first is the name of the element, the second is the content that appears between the element’s start and end tags, and the third is a hash of options that become the element’s attributes. The code above is much shorter than the original and has the added advantage that any other flash messages we set will automatically be displayed.