Never been to DZone Snippets before?

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

Yet another method to alternate table row classes (See related posts)

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

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts