Monkey patching a gem in Rails 2.3

Today I needed to add some application-specific functionality to my PaperTrail gem. Specifically I wanted to add faceted search to PaperTrail’s Version model. After a few attempts I worked out how to monkey patch a class from a gem:


# config/initializers/paper_trail_patch.rb
Version.module_eval do
  # ... new code here ...
end

Once I knew how to add code to the Version model, I needed to work out what that code would be. Fortunately Pat Allan’s Thinking Sphinx docs are excellent so it didn’t take too long to come up with:


Version.module_eval do
  belongs_to :area

  define_index do
    indexes :event  # ensures we pick up every record
    indexes :whodunnit, :facet => true

    has area_id,        :facet => true
    has created_at,     :sortable => true

    where 'reviewed = 0'
  end
end

Here I’ve defined facets for the built-in whodunnit field and a custom area_id attribute, allowing me to present the user with dropdown filters showing result counts for each filter choice.

Faceted search example

In the screenshot you can see I have two dropdown filters. Each option shows the number of results you would get if you chose it (leaving the other filter the same).

The details aren’t important. The main point is that Thinking Sphinx makes faceted search, a reasonably complicated task, easy to do.

Andy Stewart, 05 February 2010

Posted in PaperTrail, Rails | 0 comments

Hacked climate science emails

However you feel about the emails hacked from the Climatic Research Unit at the University of East Anglia, you have to admire the sysadmins who successfully kept them backed up and archived for almost 14 years.

I suppose now they’re in the public domain the backups won’t be needed any more.

Andy Stewart, 04 February 2010

Posted in Climate Change | 0 comments