Using a shared location for common code

I am a book lover, and have built up a lot of my Ruby and Rails knowledge from an ever expanding collection of books. No matter how big or small, most give me some new information or way of dealing with a problem. One of my most recent books is a little gem : Rails Pocket Reference by Eric Berry.

One bit of information I got from that was how easy it is to enter an alternative code location into your Rails configuration. It is in fact very easy, and for me was definitely a “why haven’t I done this before” moment.

All you need to do is add a

config.load_paths

declaration to the Rails application’s config/environment.rb. It needs to go within the

Rails::Initializer.run

loop. For example:

Rails::Initializer.run do |config|
  config.load_paths += %W(#{RAILS_ROOT}/../useful_objects/lib)
end

Information about doing this is there and clear in the default environment.rb so more fool me for not sussing this before.

The path in the example allows me to create a Ruby application called “useful_objects” in the same folder as my Rails applications. Any class definitions I put in the lib folder there are then available to any application that has “useful_objects” in its load path. It also gives me a central location where I can put modules for including into other classes. It also gives me a location to put unit tests for these shared classes and modules (userful_objects/test)

The more common way to manage this is probably with plug-ins. What I like with the load_path method is that I only have one place to update. If I add a new method or refactor I only need to do it in one place. Of course that could add more complication, but with me running just 3 Rails applications sharing the code, it is manageable. If I had more applications, or they were not all in the same location, then the plug-in route would be better I think.

Using a single shared location has allowed me to strip out a lot of duplication between applications: especially for things like user handling and basic text modifications. It has allowed me to slim down my main applications and make them clearer, and for me it is easy to manage.

This entry was posted in Ruby. Bookmark the permalink.