From: ara.t.howard@... Date: 2006-07-12T14:01:03+09:00 Subject: Re: alias new??? On Wed, 12 Jul 2006, Logan Capaldo wrote: > Couple of things > 1) alias_method gets executed at "compile" time. This means that it will try > to alias MagicWithNew. > > 2) This is ok because you dont want to use alias's in this case. Since #new > is almost never overriden (it's usually #initialize. Incidentally are you > sure you don't want to define #initialize instead?) it's pretty much > guaranteed that you class is using the original implementation in Class. > so we can use inheritance and super > > > module MagicWithNew > def new(*args, &block) > if some_condition > do_special_stuff fails to initialize object! you need the old 'new' here. or super. > else > super > end > end > end > > class MyClass > extend MagicWithNew # note #extend, not #include > end here is an example of a fairly robust pattern harp:~ > cat a.rb module M ClassMethods = lambda do alias_method '__new__', 'new' # correct alias of new def new *a, &b obj = __new__(*a, &b) # # do anything you want with obj here based on any condition. this is just # an example. # class << obj def answer() 42 end end obj end end def self.included other meta = class << other self end meta.module_eval &ClassMethods super end end class C include M end p C.new.answer harp:~ > ruby a.rb 42 regards. -a -- suffering increases your inner strength. also, the wishing for suffering makes the suffering disappear. - h.h. the 14th dali lama