Staying Extra DRY

Sometimes you need a little tiny function to avoid repetition. Here's a partial called packet I made.

I needed the same id for the element and the Javascript call so I pulled the id-building logic into a lambda. Now they'll never be mismatched.

<%
  pid = lambda do
    "packet-" + packet.code.downcase.gsub(/[^a-z]/, '-')
  end
%>
<dt><%= link_to_function packet.name, "Toggle.display('#{pid.call}')" %></dt>

<dd id="<%= pid.call %>" style="display: none;">
    Things about the packet.
</dd>

Yes, the id-building logic here is a bit contrived but you get the idea. For more widespread things like this I'd pull it out into a helper, but this one just didn't need it.

  • April 15, 2005
  • Dealing with rails

There are 2 comments

  1. 2 days later, Gavin Sinclair said...

    Nice idea, but wouldn't a local variable do in this case? You need the two IDs to be the same, so why call the lambda logic twice?

  2. 2 days later, Ryan said...

    Um, right. Got a little carried away there. I should have been tipped off when the lambda didn't need any arguments... anyway, this idea could still come in handy sometime.