Ruby is a very dynamic language. Even to the extent of only needing to load modules into the namespace tree when they are referenced. The idea is that it should only load and parse code when it actually needs to. This brings up a bit of a problem. How do you make plugin architectures where the framework does not need to know how many plugins there are, but that all plugins that exist in the system should be loaded, parsed and available?
This was the first issue I had with the media tagging framework, as we ultimately wanted to open the framework up to allow others to build their own plugin parsers to build on current ones. So, we needed a construct to allow the Ruby thread to load all the modules that are on disk.
I came up with the idea of implementing a sort of 'Class Factory' that would load up all the classes that exist in a particular directory. I packaged this up as a bit of DSL (Domain Specific Language).
class ObjectFactory
def self.subclasses_are_in directory
read_in_subclasses_from File.expand_path(RAILS_ROOT) + '/app/models/' + directory
end
private
def self.read_in_subclasses_from directory
Dir.glob(directory + '/*.rb') do |file_name|
require file_name
end
end
end
So, in the model directory of your application you create a subdirectory to contain the subclass files of the class you want. For instance, 'mime_types', 'parsers' etc. then define a factory to load them. Then in your head script you can pull in the particular 'factories' needed for your script and be secure in the knowledge that all the subclasses will be loaded.
class MimeFactory < ObjectFactory
subclasses_are_in 'mime_types'
end