Wednesday, July 25, 2007

Ruby : Fall through if your closure is empty?

Today my designer asked me if there's an easy way to take something like this:

<% Thing.find(:all).each { |t| %>
  Your thing is <%= t.name %><br/>
<% } %>

and add something that says "And if there were no Things found, do this other thing."

Good question!  I googled around for a bit and tried a handful of things, but couldn't get it to work the way I liked.

I found one way to do it.  Not sure it's the greatest, but it works.  Maybe somebody can chime in with a more "right" way to do it:

<% Thing.find(:all).each_with_index { |t, @thing_index| %>
   Your thing is <%= t.name %><br/>
<% } %>

<% if @thing_index == nil %>
  You poor soul, you have no things.
<% end %>

If the loop does not execute at all, @thing_index gets no value.  I'm using @thing_index instead of just thing_index, because the latter would be local to that closure and no longer exist outside of the curly braces. 

 I am sure that my syntax leaves something to be desired, there's probably a much more compact way of doing the actual fall-through check.  I did it the way I did so that I could tell the designer "You fill in this block here" and have it clearly delineated.

1 comment:

jason said...

your comments don't allow code, but try:

if Thing.find(:all).each {|t|
Your thing is t.name
} .empty?
You poor soul, you have no things.
end

sorry, had to remove the rhtml tags for it to accept.