I often want different rows in a table to alternate in color, and I do this by assigning each row a class name and styling it with CSS. This is a simple helper method designed to return a class name based on the given row count.
It is also convenient for me to assign a class to table cells based on the type of content they hold. For example, if I have a cell with a float value in it, I want to display it with a monospace font, whereas if I have a cell with a string in it, I want to display it in a serif font.
def classify( count_or_class, include_class_text = true )
if count_or_class.class == Fixnum
value = ( count_or_class % 2 == 0 ? 'even' : 'odd' )
else
value = count_or_class.to_s.downcase
end
if include_class_text
'class="' << value << '"'
else
value
end
endExample usage with alternating 'even'/'odd' row class names:
<table>
<% count = 0 %>
<% @collection.each do |value| %>
<tr <%= classify( count ) %>>
<td><%=h value %></td>
</tr>
<% count += 1 %>
<% end %>
</table>Example usage with data type class names:
<tr>
<% @columns.each do |column| %>
<% data = row.send( column.name ) %>
<td <%= classify( data.class ) %>>
<%=h data %>
</td>
<% end %>
</tr>