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:

1
2
3
4
5
6
7
8
<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:

1
2
3
4
5
6
7
<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.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s