Posted on February 14, 2006 at 9:43 pm

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

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.

Leave a comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>