cycle(first_value, *values) public

Creates a Cycle object whose to_s method cycles through elements of an array every time it is called. This can be used for example, to alternate classes for table rows. You can use named cycles to allow nesting in loops. Passing a Hash as the last parameter with a :name key will create a named cycle. The default name for a cycle without a :name key is "default". You can manually reset a cycle by calling reset_cycle and passing the name of the cycle. The current cycle string can be obtained anytime using the current_cycle method.


  # Alternate CSS classes for even and odd numbers...
  @items = [1,2,3,4]
  <% @items.each do |item| %>
    <tr class="<%= cycle("even", "odd") -%>">
  <% end %>

  # Cycle CSS classes for rows, and text colors for values within each row
  @items = x = [{:first => 'Robert', :middle => 'Daniel', :last => 'James'},
               {:first => 'Emily', :middle => 'Shannon', :maiden => 'Pike', :last => 'Hicks'},
              {:first => 'June', :middle => 'Dae', :last => 'Jones'}]
  <% @items.each do |item| %>
    <tr class="<%= cycle("even", "odd", :name => "row_class") -%>">
        <% item.values.each do |value| %>
          <%# Create a named cycle "colors" %>
          <span style="color:<%= cycle("red", "green", "blue", :name => "colors") -%>">
            <%= value %>
        <% end %>
        <% reset_cycle("colors") %>
 <% end %>
Show source
Register or log in to add new notes.
April 20, 2009
2 thanks

Cycle with first and last

I needed a cycle that was also aware of the first and last items in the collection. This is adapted from a snippet I found while Googling:

def cycle_with_first_last(object, collection, options = { })
  addition = ""
  addition += " #{options[:first]}" if object == collection.first
  addition += " #{options[:last]}"if object == collection.last
  cycle(options[:odd], options[:even]) + addition

Just put that in your helpers…

September 11, 2008
1 thank

CSS columns

You can also use this in a partial to create blocks of content into columns without setting a fixed height. This one is two columns.

.clear { clear: both;}
.block { float:left;width:200px;}

<div class="block">

<p>Content Item</p>

<%= cycle("", "<div class=\"clear\"></div>") -%>