Rails cycle helper

You all probably know the Rails helper function ‘cycle’, most commonly used to specify alternating classes when iterating over a collection :


<% for item in @items %>
  <tr class=<%=cycle('even', 'odd')%>>
    <td><%= item.name %></td>
  </tr>
<% end %>

Well, apparently it is even more usefull than I thought, and it was simply a matter of reading the rails documentation ...

  • You can cycle through more than two values: cycle(‘first’, ‘second’, ‘third’, ‘and_more’)
  • Sometimes you need multiple (nested) cycles in your views, for example, the normal alternating rows within a series of alternating tables. In that case you can pass the :name key to create ‘named cycles’ Check the rails documentation for an example.
  • And last bun not least: reset_cycle(‘cycle_name’) This makes sure that on each iteration, you will start again with your first value of the cycle list !

Maybe nothing special, but if you didn’t knew this yet, I’m sure you’ll like it :-)

Tail it !

Entries per category

  1. docpublisher (6)
  2. events (6)
  3. rails (6)
  4. ruby (15)
  5. xml (3)