DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Yet Another Method To Alternate Table Row Classes

09.09.2005
| 7094 views |
  • submit to reddit
        Use a helper function/class as such:

<%- row_class = cycle("even", "odd") -%>
<%- for item in @items do -%>
  <tr class="<%= row_class %>">
    ... use item ...
  </tr>
<%- end -%>

Put this in your application_helper.rb:

  def cycle(first_value, *values)
    values.unshift(first_value)
    return Cycle.new(*values)
  end

  class Cycle
    def initialize(first_value, *values)
      @values = values.unshift(first_value)
      @index = 0
    end

    def to_s
      value = @values[@index].to_s
      @index = (@index + 1) % @values.size
      return value
    end
  end