One of the pieces of code I find myself writing over and over again is a banner for flash messages.

<div class="error" id="error">
<%=h flash[:error] %>
</div>
<div class="notice" id="notice">
<%=h flash[:notice] %>
</div>

That already is six lines of code that I will never care about again. And, to date, I’ve written then 5 times. They get worse, though, if I want those divs to be hidden when there is no message to display. I could wrap them like this:

<% if flash[:notice] %>
...
<% end %>

And if there is no message, the block will be absent from the page. But inevitably, I want to show those messages on an XHR, so my layouts get a little more complex:

<div class="error" id="error" <%= "style=\"display:none;\"" if flash[:error] %>

This is a perfect candidate for refactoring. My final product looks like this:

def flash_message(key, options={})
message = flash[key] || ""
options.reverse_merge!(:class => "flash #{key}", :id => "flash_#{key}")
options.merge!(:style => "display:none;") if message.empty?
content_tag :div, message, options
end

It replaces the six lines above with these two:

<%= flash_message :notice %>
<%= flash_message :error %>

I’ve tucked it into a plugin of other private conventions and will drop it into every new Rails app I write.