Rails-Style Dynamic Finders For Ruby Arrays

One of my favorite little elegances in Ruby on Rails is ActiveRecord’s dynamic finder magic. It lets you perform simple model queries with as much readability as is conceivable in a method call:
# Normal ActiveRecord call - tasty, but still a bit bland.
Sandwich.find(:all, :conditions => ['meat = ? and tastiness = ?', 'turkey', 'medium'])

# Dynamic finder - unequivocally delicious. Try it with chocolate!
Sandwich.find_all_by_meat_and_tastiness('bacon', 'very')
Lost in the wonders of such syntactic saltiness (er, sugariness), I frequently found myself using these kinds of commands on arrays of model objects I had already retrieved from the database. Naturally enough, all I encountered was a variety of colorful exceptions, but I continued to dream of a world where dynamic finders worked for arrays, too.

Fortunately, a little experimentation, a covert glance at the ActiveRecord code, and a timely discovery of the wonders of inject led me to a successful implementation:

Read the rest of this entry »