HOW TO: Easily output alternating item styles via metaprogramming

I always need to apply alternating item styles when outputting a collection, here’s what I’ve been using recently.

In the app helper I define this method:

def alternate(items,alt=false
items.map{|i| i.class}.each { |k|
k.class_eval {attr_accessor :alt}}
items.each { |i| i.alt, alt = alt, !alt }
end

When I call the partial I wrap the collection with this method:

<%= render :partial => ‘story’, :collection => alternate(@stories) %>

Now in the partial each object in the collection has the alt attribute available:

  • ">

    Obviously I’m making the assumption that the objects don’t already have/use an alt attribute. Anyone solving this similarly?

    • Nathan
  • To be honest I’m not really following your code.

    items.each { |i| i.alt, alt = alt, !alt } What is this doing?

    I must be missing something because it seems that every call to alt should return false from the setup in the alternate method.

    My mind went to the cycle method, but I’m not sure if that fits or not since I don’t follow your code.

    Anyway the docs are

    http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M000628

    Cheers

    Daniel

    Shai,

    haha - ferocious? you’re right

    your solution worked (just needed another ?):

  • thanks,

    nathan

  • If you just want to use another style for every odd row, I'm using something
    like this:

    <% @page.items.each do |item| %>
       ...
       <tr class="<%= cycle("even", "odd") %>">
       ...
    <% end %>

    API:
    http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M000628

    Regards,
    Timo