From: Matthew Moss Date: 2006-01-31T01:36:07+09:00 Subject: Re: [QUIZ] Port a Library (#64) There aren't any particular libraries I've used anytime recently... all my work is in-house code. But I took a quick glance over CPAN for something relatively small and simple... the latter because I stopped coding in Perl years ago and don't remember all the syntax very well, especially the stuff that has been added for objects. In any case, I found a simple library called Trampoline by Steven Lembark which allows you to create an object but delay actual construction... which is useful to have something with expensive construction cost ready to go but not actually constructed until used. Below I provide a really basic implementation that is probably not rock-solid and could probably be done better ... I'm still such a n00b, especially when it comes to metaclasses (or eigenclasses, or whatever they want to be called this week). It also doesn't do everything the Perl lib did, just what I found useful and could understand. Anyway, here's the code (trampoline.rb), with a couple of use examples at the bottom. module Trampoline # Instance methods class Bounce def initialize(cons, klass, *args) @klass, @cons, @args = klass, cons, args end def method_missing(method, *args) @obj = @klass.send(@cons, *@args) unless @obj @obj.send(method, *args) end end # Class methods class << Bounce alias_method :old_new, :new def new(*args) old_new(:new, *args) end def method_missing(method, *args) old_new(method, *args) end end end And now, example use. Obviously, this class is not in need of delayed construction; just using it as an example. require 'trampoline' class Logger def initialize(prefix) puts 'Constructing Logger...' @prefix = prefix end def Logger.make(prefix) Logger.new(prefix) end def log(msg) puts "#{@prefix}: #{msg}" end end puts "start" errors = Trampoline::Bounce.new(Logger, 'ERROR') puts "made bouncer, about to log message" errors.log('Hello, world!') puts "about to log second message" errors.log('Goodbye, world!') puts "message logged" # This is really the same, but eventually calls Logger.make to construct. puts "start" warns = Trampoline::Bounce.make(Logger, 'WARNING') puts "made bouncer, about to log message" warns.log('Hello, world!') puts "about to log second message" warns.log('Goodbye, world!') puts "message logged" Output from the example code: start made bouncer, about to log message Constructing Logger... ERROR: Hello, world! about to log second message ERROR: Goodbye, world! message logged start made bouncer, about to log message Constructing Logger... WARNING: Hello, world! about to log second message WARNING: Goodbye, world! message logged