Skip to content

Instantly share code, notes, and snippets.

@dce
Created October 19, 2011 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dce/1298491 to your computer and use it in GitHub Desktop.
Save dce/1298491 to your computer and use it in GitHub Desktop.
<% list_items_for @products do |product| %>
<%= link_to product.name, product %>
<% end %>
<!--
<li class="first"><a href="/products/1">Product #1</a></li>
<li><a href="/products/2">Product #2</a></li>
<li class="last"><a href="/products/3">Product #3</a></li>
-->
<% list_items_for @products, :class => "product" do |product| %>
<%= link_to product.name, product %>
<% end %>
<!--
<li class="product first"><a href="/products/1">Product #1</a></li>
<li class="product"><a href="/products/2">Product #2</a></li>
<li class="product last"><a href="/products/3">Product #3</a></li>
-->
<% list_items_for @products, :class => lambda { |p| "active" if p.active? } do |product| %>
<%= link_to product.name, product %>
<% end %>
<!--
<li class="first"><a href="/products/1">Product #1</a></li>
<li class="active"><a href="/products/2">Product #2</a></li>
<li class="active last"><a href="/products/3">Product #3</a></li>
-->
def list_items_for(collection, opts = {}, &block)
if collection
opts.reverse_merge!(:first_class => "first", :last_class => "last")
try_call = lambda do |obj, item|
obj.respond_to?(:call) ? obj.call(item) : obj
end
concat(collection.map { |item|
attributes = {
:class => [
try_call[opts[:class], item],
(opts[:first_class] if collection.respond_to?(:first) && item == collection.first),
(opts[:last_class] if collection.respond_to?(:last) && item == collection.last),
].compact * " "
}
if opts[:attrs]
attributes.merge! try_call[opts[:attrs], item] || {}
end
content_tag (opts[:tag] || :li), capture(item, &block), attributes
}.join("\n"))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment