From: "ara.t.howard" Date: 2008-08-05T05:35:19+09:00 Subject: Re: Is it ellegant to use a global variable to store a Logger object? On Aug 4, 2008, at 1:43 PM, Chuck Remes wrote: > I hate to resurrect this thread, but I have a problem that I can't > seem to solve and I didn't want to rehash the original suggestions. > > I need a global Logger within a framework I wrote. The trouble is > that I need to be able to instantiate multiple independent copies of > this framework within the same Ruby runtime (specifically Jruby). > > If I do this it doesn't work for more than one instance: > > module Namespace > Logger = # instantiate some logger > > module Submodule > class Klass > def foo > Logger.log("in Klass#foo") > end > end > end > end > > I can load and instantiate this only once in the runtime. If I try > to do it a second time, it's like I have reopened the class/module > and Logger gets redefined. Each instantiation shares the same global > Logger which is *not* what I want. I want each one to have their own > instance. > > Is this possible? Any recommendations for solving it? > > cr > > something similar to: module Namespace module Logger def Logger.key *key @key = key.first unless key.empty? end def instance @instances = Hash.new{|h,k| @instances[key || :default ] ||= new} end %w( debug info warn error fatal ).each do |method| module_eval <<-code def Logger.#{ method }(*a, &b) instance.#{ method }(*a, &b) end end end end end Namespace::Logger.key Thread.current.object_id # or something unique Namespace::Logger.info{ 'foobar' } a @ http://codeforpeople.com/ -- we can deny everything, except that we have the possibility of being better. simply reflect on that. h.h. the 14th dalai lama