Over a million developers have joined DZone.

Yet Another Method To Alternate Table Row Classes

·
Use a helper function/class as such:

<%- row_class = cycle("even", "odd") -%>
<%- for item in @items do -%>
  
    ... use item ...
  
<%- 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
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}