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.
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.