Say you’re using ActiveRecord, and you want to write a query that uses the same parameter value several times. For instance:


  Lead.find(:all, :conditions => 
    ['created_at > ? AND updated_at > ? AND published_at > ?', 
      10.days.ago, 10.days.ago, 10.days.ago])

Hmmm… that’s not very DRY, is it? How about we spiff it up some with a bit of Ruby hackery:


  Lead.find(:all, :conditions => 
    ['created_at > ? AND updated_at > ? AND published_at > ?', 
      *([10.days.ago] * 3)])

That works, and it’s probably the shortest solution you’ll find, but it has a few problems. Most glaringly, we’re still not really DRY, because the idea that there are three query parameters is repeated in both the query itself and in the substitution values. Named parameters to the rescue:


  Lead.find(:all, :conditions => 
    ['created_at > :time_limit AND updated_at > :time_limit AND published_at > :time_limit', 
      {:time_limit => 10.days.ago}])

While this is actually the longest solution character-wise, it’s the shortest conceptually, and that’s the way we like it. The one other thing I’d want to do in a case like this is look at the underlying data model and make sure there’s a good reason to repeat the parameter like that… but that’s a topic for another day.

Named parameters are an oft-neglected option in ActiveRecord, even though folks like Robby were riffing on them over a year ago. They’re a major DRY’ing agent, so add them to your toolbox today!

Posted by Nathaniel on Nov 10th, 2006

You can still contact Nathaniel at nathaniel@terralien.com