From: Andrea Dallera Date: 2010-03-16T03:48:40+09:00 Subject: Re: Overriding new? Hei, I am uncertain about what to do: on one side I'm very aware that it would be a huge hack and, before all, using this kind of "template method" in the base class, and having every element to inherit from it, is very unflexible. On the other side i've been using freightrain for quite a while now and i really really like the syntactic sugar, so things like MyFactory.getInstance() do # user defines their behavior here end as Walton (which i thank for the pointer) suggested are a big no no. I like this way of doing it: def new(*a,&b) obj = allocate #do your stuff obj.send(:initialize,*a,&b) return obj end What do you think about it? Aside from the performance hit (in my case i really don't case), are there any motivation i'm not seeing for not using it? Also forbidding to specify the constructor would be a way to go but i'd like to allow as much freedom as possible. -- Andrea Dallera http://github.com/bolthar/freightrain http://usingimho.wordpress.com On Tue, 2010-03-16 at 02:24 +0900, Chuck Remes wrote: > On Mar 15, 2010, at 12:07 PM, Tony Arcieri wrote: > > > On Mon, Mar 15, 2010 at 7:41 AM, Andrea Dallera wrote: > > > >> Hei Chuck, > >> > >> that's exactly what i was trying to avoid. > > > > > > One way to avoid it is to override new. You can use the "allocate" method > > to create a new object instance without invoking its constructor. Name the > > superclass's "initialize" method something different, like preinitialize, > > and invoke that yourself. Be sure to invoke initialize too, if it's > > defined. > > > > I've used this approach in frameworks where I intend for users to subclass, > > but my general impression nowadays is I should use a lot cleaner base class > > that doesn't need these sorts of hax, or not expect users to ever define > > their own constructor. > > I like Tony's final suggestion. In your base class initialize method, have it make a call to post_initialize. All subclasses should then create a post_initialize method if they need to do any construction (or leave it empty). > > This technique is used in Eventmachine since its internals like to control when and how classes are instantiated. > > cr > > >