link_to as a block helper
June 19th, 2007When it comes to creating helpers for the view portion of satisfaction, I’ve started taking the approach that once I see something “ugly” twice in the rhtml that it should be extracted out into a helper. In many cases, before that.
Today’s wart? link_to calls that have html for the text content. take for example:
<%= link_to "<strong>#{product.name}</strong><span>#{pluralize(product.topic_count(company), 'topic')}</span>", href, :class => "product_label" %>
ewww… and that doesn’t even get into having href defined above in a <% %> block. So, I extended link_to with the help of alias_method_chain such that it will take a block argument instead of the its normal first parameter.
<% link_to browse_url(product), :class => "product_label" do %> <strong><%= product.name %></strong> <span>(<%= pluralize(product.topic_count(company), 'topic') %>)</span> <% end %>
Much more readable. See the code block_link_to.rb












October 1st, 2007 at 4:09 pm
Your example code blocks are invisible in Safari 3.
October 1st, 2007 at 4:52 pm
Thanks meekish, I’ve fixed the markup.
October 7th, 2007 at 9:14 am
A general question: When and why should we go the way to just override in the helpers: http://opensoul.org/2006/08/04/tip-overriding-link_to-to-accept-a-block/ and when should we go your way?
If you don’t use your code to transform it into a plug-in, where are the advantages to go the (more verbose/complicated) way
October 7th, 2007 at 11:04 am
The only advantage of my method is that it provides the same benefit as any use of aliasmethodchain: It doesn’t hide the original method, and it makes it explicit what pattern you are using.
Please note you can further reduce the meat of my code to:
def linktowithblock(args, &block) return linktowithoutblock(args) unless block concat(linktowithout_block(capture(&block), args), block.binding) endBasically the same, just a little different personal style on the conditional.