A529b78031f700ca2005bdbd1af5ee7b

I have this function in my view helper which will piece together a list of item categories.
If the number of categories is less than 3 then just show the list. If there is more than 3 items then wrap the remaining items in a div with the class 'hidden' and append a link to the list which will show more items.

def format_category_list(sub_categories)
    count = sub_categories.count
    list = ""
  
    if count <= 3
      sub_categories.each do |category|
        list << content_tag(:li, link_to(category.name, root_path))
      end
    else
      sub_categories[0..2].each do |category|
        list << content_tag(:li, link_to(category.name, root_path))
      end
      list << "<div class='hidden'>"
      sub_categories[3..count].each do |category|
        list << content_tag(:li, link_to(category.name, root_path))
      end
      list << "</div>"
      list << content_tag(:li, link_to('Show more', nil, :class => 'show-more'))
    end

    list
  end

Refactorings

No refactoring yet !

D41d8cd98f00b204e9800998ecf8427e

op

August 24, 2010, August 24, 2010 11:28, permalink

No rating. Login to rate!

A little shorter..

def format_category_list(sub_categories)
  list = ""
  
  sub_categories[0..2].each do |category|
    list << content_tag(:li, link_to(category.name, root_path))
  end

  if sub_categories.count > 3
    list << "<div class='hidden'>"
    sub_categories[3..-1].each do |category|
      list << content_tag(:li, link_to(category.name, root_path))
    end
    list << "</div>"
    list << content_tag(:li, link_to('Show more', nil, :class => 'show-more'))
  end

  list
end
A8d3f35baafdaea851914b17dae9e1fc

Adam

August 24, 2010, August 24, 2010 15:30, permalink

1 rating. Login to rate!
def format_category_list(categories)
  link_to_categories(categories.first(3)).tap do |output|
    if categories.size > 3
      output << content_tag(:div, :class => 'hidden') { link_to_categories(categories.slice(3..-1)) }
      output << content_tag(:li, link_to('Show more', nil, :class => 'show-more'))
    end 
  end
end

def link_to_categories(categories)
  categories.map { |category| content_tag(:li, link_to(category.name, root_path)) }
end
0dba10774351090583ce306ef0ca805b

Les Nightingill

October 10, 2010, October 10, 2010 21:33, permalink

No rating. Login to rate!

My approach would be to move the counting logic back into the controller.

# in the controller

@categories = Category.all(limit => 3)
@more_cats = Category.all - @categories
<%= render :partial=>'cat', :collection => @categories %>
<% if !@more_cats.empty? %>
   <li><%= link_to 'Show more' ...etc %>
<div class='hidden'>
<%= render :partial=>'cat', :collection => @more_cats %>
</div>
<% end %>
<li><%= link_to ... etc   %>

Your refactoring





Format Copy from initial code

or Cancel