views:

130

answers:

1

In Rails 3 I use the following helper in order to get a even-odd-coloured table:

def bicolor_table(collection, classes = [], &block)
  string = ""
  even = 0
  for item in collection
    string << content_tag(:tr, :class => (((even % 2 == 0) ? "even " : "odd ") + classes.join(" "))) do
        yield(item)
    end
    even = 1 - even
  end
  return string
end

And I use it in my views like this:

<%= bicolor_table(services) do |service| %>
    <td><%= image_tag service.area.small_image %></td>
    <td><%= link_to service.title, service %></td>
<% end %>

Now, I have to migrate the application to Rails 2. The problem is Rails 2 doesn't use Erubis, so when it finds a <%= whatever %> tag, it just calls whatever.to_s. So, in my case, this result in trying to execute

(bicolor_table(services) do |service|).to_s

With the obvious (bad) consequences. The question is: am I wrong in principle (like "helpers shouldn't work this way, use instead …") or should I look for a workaround?

Thanks.

+3  A: 

This might not answer your question, but there is a much simpler way to achieve even/odd color table, using the cycle command

 @items = [1,2,3,4]
  <table>
  <% @items.each do |item| %>
    <tr class="<%= cycle("even", "odd") -%>">
      <td>item</td>
    </tr>
  <% end %>
  </table>

Hope this at introduces you to a cool Rails utility

Jonathan
This is a good and useful way to achieve what I needed in this occasion, but still I'm wondering if passing blocks to helpers is an acceptable behavior. Thanks for your answer! :-)
Alberto