Thursday, October 20, 2005

Simple Row Style Alternator

In your view (rhtml):

<table>
  <thead>
    <tr>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
  <% for user in @users %>
    <tr class="<%= row_style %>">
      <td><%= user.name %></td>
    </tr>
  <% end %>
  </tbody>
</table>

In your helper (rb): Updated!

  def row_style
    @row_index ||= 0
    @row_index += 1
    @row_index % 2 == 0 ? "Even" : "Odd"
  end

5 comments:

  1. Forrest,
    Almost - you'll want two pipes, as in ||=
    irb(main):001:0> foo = 0 if !foo
    => 0
    irb(main):002:0> foo = 1 if !foo
    => nil
    irb(main):003:0> foo
    => 0
    irb(main):004:0> bar ||= 0
    => 0
    irb(main):005:0> bar ||= 1
    => 0
    I'm still trying to learn Ruby, too - I think it works as follows:
    a |= 0 expands to a = a | 0.
    b ||= 0 expands to b = b || 0.
    The | operator evaluates the two operands as boolean values and returns true if either is true (not short-circuiting). Seems most anything except nil and false eval to true here, including 0. I'm pretty sure on this, but can't find a reference to corroborate it.
    The || operator returns the first operand if it evaluates to true; otherwise it returns the second operand. So, given b = b || 0, if b is nil, (b || 0) returns 0.
    Can a Ruby expert step in and confirm/clarify?

    ReplyDelete
  2. Jason,
    You are correct. The ||= performs what I was thinking of. I didn't even run |= through irb. Guess I should do that from now on :o) The ||= operator is also explained in the "Agile Web Development With Rails" book on page 479. Thanks for the correction and help.

    ReplyDelete
  3. Nice! Thanks for the suggestion, I'll update the post to show this approach.

    ReplyDelete
  4. Whoops.
    cycle('even','odd') is what I meant to say. Check it out in the rails api.

    ReplyDelete