Samuel Williams 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

Leave a comment

Please note, comments must be formatted using Markdown. Links can be enclosed in angle brackets, e.g. <www.codeotaku.com>.