Saturday, November 10, 2007

Rails: Integer#even?

Documentation
None

Usage
The Integer#even? method is helpful when adding zebra striping to views.

For example:
  <% @customers.each_with_index do |customer, index| %>
<div style="color:<%= index.even? ? "white" : "gray" %>">
<%= customer.name %>
</div>
<% end %>

Test

require 'rubygems'
require 'active_support'
require 'test/unit'
require 'dust'

unit_tests do
test "10 is even?" do
assert_equal true, 10.even?
end
end

2 comments:

  1. Anonymous4:32 PM

    The above usage assumes you have rows that are never deleted. To ensure that the "zebra striping" always occurs one should look into the cycle method provided by rails:
    http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M000634

    ReplyDelete
  2. The above comment is not entirely accurate. "Each with index" refers to the array @customers, that is populated from the controller. "Index" refers to the "index" in the array, not the ActiveRecord ID from the database.

    I agree, though, on the point about cycle. Cycle is much more powerful inside an iteration of a loop because it accepts a variable amount of values:


    <div style="color:<%= cycle("white", "gray", "red")" %> >

    ReplyDelete

Note: Only a member of this blog may post a comment.