Monday, October 30, 2006

Rails: Autoloading Gems in Vendor

It's no secret that I'm a big fan of RubyGems. Due to this bias, I tend to package up all my reusable code as RubyGems. Then, when I'm developing a new Rails application I gem unpack [gem] each of the gems I'm using in the vendor directory. This works out well, but I am stuck maintaining the require [path/to/gem] statements that are necessary for loading the libraries.

To resolve this maintenance pain I put the following code in environment.rb.
Dir[File.dirname(__FILE__) + "/../vendor/*"].each do |path|
gem_name = File.basename(path.gsub(/-\d+.\d+.\d+$/, ''))
gem_path = path + "/lib/" + gem_name + ".rb"
require gem_path if File.exists? gem_path
end
The above script relies on a few RubyGems conventions: 3 digit versioning and a file in lib that requires all relevant ruby files for the library. I'm comfortable with these assumptions; however, not all gems follow them. For example, postgres-pr uses a ruby file named postres.rb to load the library. For situations like these, I still need to do an explicit require.


Comments:
Check out Rick Olson's GEMs plugin which will be rolled into core after the 1.2 release: http://svn.techno-weenie.net/projects/plugins/gems/
 
This plus the gems.rake task Rick made will really help this be more widely used. Thanks!
 
I've also started some ideas on freezing & linknig gems into rails apps - http://rubyforge.org/projects/gemsonrails/

Not officially released or advertised yet, but its very nice so far.
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?