ActiveRecord Find with block

February 14th, 2006

Have you ever wanted to pass a block to an ActiveRecord model in order to pre-filter results?

:::ruby
module ActiveRecord
  class Base
    class << self 
      alias_method :find_without_filter, :find
      def find(*args)
        records = find_without_filter(*args)
        if block_given?
          filtered = []
          records.each do |record| 
            filtered << record if yield(record)
          end
          filtered
        else
          records
        end
      end
    end
  end
end

This is a quick and dirty hack of a plugin, but it does the trick. I’m far from satisfied though. Soliciting opinions from those in the know. Email me.