link_to as a block helper

When 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

4 Responses to “link_to as a block helper”

  1. meekish Says:

    Your example code blocks are invisible in Safari 3.

  2. nullstyle Says:

    Thanks meekish, I've fixed the markup.

  3. nicolash Says:

    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-lin... 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

  4. nullstyle Says:

    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: <pre class="shruby"> def linktowithblock(args, &block) return linktowithoutblock(args) unless block concat(linktowithoutblock(capture(&block), args), block.binding) end </pre>

    Basically the same, just a little different personal style on the conditional.

Leave a Reply