From: Logan Capaldo Date: 2006-07-12T13:49:32+09:00 Subject: Re: alias new??? On Jul 12, 2006, at 12:07 AM, David Chelimsky wrote: > I've seen this work before: > > module MagicWithMethodMissing > alias_method :__orig_method_missing, :method_missing > def method_missing(sym, *args, &block) > if some_condition > #do special stuff > else > __orig_method_missing(sym, *args, &block) > end > end > end > > class MyClass > include MagicWithMethodMissing > end > > I want to do the same thing w/ :new on the class > > module MagicWithNew > alias_method :__orig_new, :new > def new(*args, &block) > if some_condition > #do special stuff > else > __orig_new(*args, &block) > end > end > end > > The question I have is how do I get this included in the meta class > of MyClass? > > Thanks, > David > > > 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 else super end end end class MyClass extend MagicWithNew # note #extend, not #include end