Plugging into Rails
So, you’ve got a new
acts_as_chunky_bacon mixin you want to add to ActiveRecord, but those villianous core team members have turned you down and called you unworthy. What other options do you have? People need this mixin. You understand that in Ruby, things ought to act like chunky bacon.
It used to be (in that dim age before the 2005 RubyConf) that your only recourse was to package the thing up and tell people to go through the hassle of putting your mixin somewhere, adding it to their load-path, and requiring the file.
No more! Edge Rails now sports a very-simple-but-effective plugin system. You, as the author, can now give someone a zip file and tell them to simply uncompress it into their
vendor/plugins directory—and that’s it. No more configuration required by the user.
All you, as the author, need to do is create a project with the following directory structure:
acts_as_chunky_bacon/ acts_as_chunky_bacon/init.rb acts_as_chunky_bacon/lib acts_as_chunky_bacon/lib/acts_as_chunky_bacon.rb
When the application starts, the
lib directory will be automatically added to the load path, and the
init.rb automatically loaded. (Either may be absent.) The
init.rb just needs to do something like the following:
ActiveRecord::Base.send :include, ActsAsChunkyBacon
What does this mean? It means that consumers of your plugin only need to drop your project in their
vendor/plugins directory, and then start applying it to their own model objects:
class PoignantGuide < ActiveRecord::Base acts_as_chunky_bacon :from => "chapter 3" ... end
Currently, we at 37signals are using this plugin system to share code between our various applications. We are using it for things like email notification on errors, or common
before_filter’s, or our web service infrastructure that allows Backpack and Basecamp to integrate with Writeboard.
I really like this new plugin system. It probably isn’t perfect, yet—I’m sure people will find ways to make it even handier—but it really makes it a lot easier to share code. Hopefully it will also make it easier for the Rails core team to say “no” to many proposed new features, since many of them can now be more easily shared as third-party additions.