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 !
op
August 24, 2010, August 24, 2010 11:28, permalink
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
Adam
August 24, 2010, August 24, 2010 15:30, permalink
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
Les Nightingill
October 10, 2010, October 10, 2010 21:33, permalink
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 %>
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.