HOW TO: Easily output alternating item styles via metaprogra

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
  • On 7/3/07, blinking bear [email protected] wrote:

    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

    Cheers
    Daniel

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

  • ">
  • seems kinda ferocious to me… you could use the partial counter to
    count even uneven objects, and then style them accordingly:

    ===========some.rhtml===============

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

    =======_story.rhtml=================

  • works for ya…?

  • Shai,
    haha - ferocious? you’re right

    your solution worked (just needed another ?):

  • thanks,
    nathan

  • your solution worked (just needed another ?):

  • oh yea, thanks…glad it helps :slight_smile:

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

    <% @page.items.each do |item| %>

    "> ... <% end %>

    API:

    Regards,
    Timo