From: "Simon Kröger" Date: 2006-04-22T21:23:28+09:00 Subject: Re: Synchronized object Thanks a lot, but consider this: ------------------------------------------------------------------------- require 'monitor' class AutoMonitor include MonitorMixin def initialize(obj) mon_initialize @obj = obj end def method_missing(sym, *args, &block) synchronize do @obj.send(sym, *args, &block) end end end def sync obj meth = obj.methods - %w{__send__ __id__} klass = class << obj.extend(MonitorMixin); self; end meth.each{|m|klass.module_eval "def #{m}(*a,&b)synchronize{super}end"} obj end hash = {"test1" => 1, AutoMonitor.new("test2") => 2, sync('test3') => 3} p hash.include?("test1") #=> true p hash.include?(AutoMonitor.new("test1")) #=> false p hash.include?("test2") #=> false p hash.include?(AutoMonitor.new("test2")) #=> false #but p hash.include?("test1") #=> true p hash.include?(sync("test1")) #=> true p hash.include?("test3") #=> true p hash.include?(sync("test3")) #=> true ------------------------------------------------------------------------- Of course it is possible to enhance AutoMonitor to handle these cases, but i like the 4 liner. :) If only i could make this module_eval go away. (or at least use the block form) cheers Simon Patrick Hurley wrote: > On 4/21/06, David Corbin wrote: > [...] > require 'monitor' > > class AutoMonitor > include MonitorMixin > > def initialize(obj) > mon_initialize > @obj = obj > end > > def method_missing(sym, *args, &block) > synchronize do > @obj.send(sym, *args, &block) > end > end > end > > class Class > def monitored_new(*args, &block) > AutoMonitor.new(new(*args, &block)) > end > end > > > Something like this and then you can: > > f = Foo.monitored_new > > pth