Search code examples
ruby-on-railshelpercyclealternating

Rails cycle helper with a few exceptions


I'm using the Rails cycle() helper method in the standard way with table rows to make alternating rows different background colors. However, I want an occasional row or two (that match certain criteria) to be a different, third color, without interrupting the cycle.

In other words, I want rows like:

white
black
red
black
white
black
white

Instead of:

white
black
red
white
black
white

What's the best way to do this?


Solution

  • Got to store it in a temporary variable and make the call to cycle() to ensure it is up-to-date.

    <%
    class = cycle('white', 'black', :name => 'colors')
    class = 'red' if should_be_highlighted
    %>
    <tr class="<%= class %>">
    

    You could wrap this up nicely in your own helper.