Loading Anonymous Ruby Classes

Author: Samuel Williams When: Friday, 16 October 2009

The following is an excerpt from a project I am working on. This function reads ruby code and turns it into an anonymous class. This class is then instantiated and returned. It allows you to load code from a file dynamically - it can also be reloaded.

def load_file(path, superclass = Object)
	if File.exist?(path)
		klass = Class.new(superclass)
		klass.class_eval(File.read(path), path)
		return klass
	else
		return nil
	end
end
 
if plugin_klass = load_file("plugin.rb")
	plugin = plugin_klass.new([1, 2, 3])

	puts plugin.process("Hello World")
end
# "plugin.rb"
def initialize(foo)
	$stderr.puts "Plugin Loaded #{foo.inspect}"
end
 
def process(data)
	return data.reverse
end

The goal for this is to provide a class loader for a web framework experiment I'm working on. Plugins can be loaded and reloaded as many times as is required.


Comments

There are currently no comments.
[City], [Country]
Publicly displayed.
Your email won't be displayed.
The following tags are preserved: <pre>, <em> and <a>. All comments are moderated.

Please note, you can leave a comment that uses (limited) XHTML and Textile syntax.