Thursday, September 03, 2009

A tiny empty shortcut

I think I've written about this before, by monkeypatching an empty method on the Array class that takes a block and executes it only if the array is empty.  But anyway, for some of you, you might see something like this taking place often:

<ul>
<% if @messages.empty? %>
There are no messages
<% else %>
<% @messages.each do |m| %>
<li><%= m.body %></li>
<% end %>
</ul>

To clean it up a little, you can do:

<ul>
<% if @messages.each do |m| %>
<li><%= m.body %></li>
<% end.empty? %>
<li>There are no messages</li>
<% end %>
</ul>

Or else if each of your items is a partial, use the :collection method.

Posted via email from The Web and all that Jazz

No comments:

Post a Comment