Adding acts_as_solr to an extrenal gem


November 5th, 2009

Problem

Say you have a third party database that you need your rails applications to access. But of course you want it to be modular and use it again for other applications, so you write a gem to provide access to the non-rails standard database. Now you want to add in acts as solr to search across the database from your application.

Solution

Acts as solr is a rails plugin and requires a solr server instance be running and therefore its not necessarily correct to add in the acts_as_solr plugin into your gem library. The consuming applications should be responsible for indexing what they and and how they want it. So a common trick is used to add in the application specific functionality into the gem. Initializers are used to inject the desired functionality into the gems classes. Given you have your gem named third_party_db_gem, create a file in config/initializers named something along the lines of third_party_db_gem_extensions.rb. And put in some code like:

require 'third_party_db_gem' ThirdPartyModel.class_eval do include ActsAsSolr acts_as_solr :fields => [:name, :email, :phone, job] end

Explanation

So first we had to require our gem, because our gem hasn't been loaded yet. Then we do a class_eval to inject our solr definition into one of the models. You would repeat that block for every class you wanted to index. Here's Jay Fields article more on class and instance eval.

Leave a Reply