Rails cycle helper
Posted by Stijn Pint on Aug 20, 2008
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 :-)