Loading Anonymous Ruby Classes
Author: Samuel Williams When: Friday, 16 October 2009April 2009
May 2009
August 2009
September 2009
October 2009
- Building a Concrete Bath
- LED Lighting Comparison
- Thinking about Programming Languages
- How To Be A Consultant
- Lucid Programming Dojo
- Exim4 + ClamAV + SpamAssassin
- Secure login using AJAX
- Ramaze And Rack
- ActiveMerchant
- Concurrency And Immutability
- Floating Point Numbers
- Programming And Debugging
- Useful jQuery Plugins
- Loading Anonymous Ruby Classes
- 尺八 (Shakuhachi)
- Card Trick
- Object Oriented C
- Gemcutter
- Writing Clearly
- Richard Stallman In Christchurch
- Magnatune
- Client Side Graphing
- Zena CMS
November 2009
February 2010
March 2010
April 2010
May 2010
June 2010
July 2010
August 2010
September 2010
December 2010
January 2011
March 2011
May 2011
August 2011
September 2011
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
Please note, you can leave a comment that uses (limited) XHTML and Textile syntax.