From: Martin Jansson Date: 2006-07-23T15:56:55+09:00 Subject: Re: Set an instance variable before and after initialize Trans wrote: > Martin Jansson wrote: >> If possible, I would like to set a instance variable in an object before >> and after its initialize method is executed. >> >> I've been looking at Class#new but it doesn't seem to have access to a >> reference to the object in creation. > > class Klass > def self.new( *args, &blk ) > o = allocate > o.instance_variable_set( "@foo", "anything") > o.initialize( *args, &blk ) > o.instance_variable_set( "@bar", "anything") > o > end > > You could also you #instance_eval { @foo = "anything } > > T. This break the chain of inheritance. You would have to reimplement all classes that you use; it would be more complicated to use then Thread even if it would have the advantage that you could circumvent some of Threads limitations. I'm not even sure that it would behave correctly. Class#new seem to do more then call allocate and initialize. But I could be wrong. Here is the C code for Class#new: VALUE rb_class_new_instance(argc, argv, klass) int argc; VALUE *argv; VALUE klass; { VALUE obj; obj = rb_obj_alloc(klass); rb_obj_call_init(obj, argc, argv); return obj; } I've looked at rb_obj_call_init, but I can't seem to find it at the moment. My current hack has an ActiveObject class that I use instead of Object. In this class I have a method called body instead of initialize. initialize is already used to set that damn variable and to call body and can not be rewritten. All this of course breaks the chain of inherritance. -- Posted via http://www.ruby-forum.com/.