Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Rails 3 to Rails 2: helpers with blocks

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.

like image 358
Alberto Santini Avatar asked Feb 27 '23 08:02

Alberto Santini


1 Answers

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

like image 160
Jonathan Avatar answered Mar 08 '23 16:03

Jonathan