This post originated from an RSS feed registered with Ruby Buzz
by Eigen Class.
Original Post: Plugins in your Ruby application
Feed Title: Eigenclass
Feed URL: http://feeds.feedburner.com/eigenclass
Feed Description: Ruby stuff --- trying to stay away from triviality.
I remember spending some time implementing a plugin framework in C++ some ~10
years ago. Things have changed greatly since, and when I had to do the same
in Ruby some days ago for
my Ruby script for the wmii window manager it took me but a few
minutes.
Goals
This is yet another task that becomes so easy in Ruby it seems to fade out,
so to say, the same way many design patterns are trivial and hardly deserve
to be named anymore.
There are at least two things a plugin framework should do:
allow the user to drop plugins into some directory and have them loaded
register the functionality exposed by each plugin so as to use it either automatically or on demand
The first part is but a simple iteration
Dir["#{PLUGIN_DIR}/*.rb"].each{|x|loadx}
Registering
As for the second, there are many ways to do it, but it definitely looks
better when plugin registration is automagical and the plugin definition seems
purely declarative. Several ideas come to mind, as there are quite a few
hooks we can use for that.
Class#inherited
Class#inherited is the most obvious choice (I feel); it'd look like this
class PluginBasedef self.inherited(child)# register child somewhere# just to give a complete example:PluginBase.registered_plugins<<childend@registered_plugins=[]class <<self;attr_reader:registered_pluginsendend