From: dblack@... Date: 2006-11-05T03:34:40+09:00 Subject: Re: Redefining a class Hi -- On Sun, 5 Nov 2006, Robert Dober wrote: > On 11/4/06, ara.t.howard@noaa.gov wrote: >> >> On Sat, 4 Nov 2006, Robert Dober wrote: >> >> > Hi all >> > >> > Recently we had a thread where we talked about redefining a class. >> > The usefuleness of that did not come into my mind before. >> > >> > Does somebody know a way to redefine a class (without the "already >> > initialized constant " warning)? >> > And if there is none, which I suspect, might it not be nice to have one? >> >> >> c = Class.new{ >> def initialize >> @x = 'foo' >> end >> } >> o = c.new >> >> c = Class.new{ >> def initialize >> @x = 'bar' >> end >> } >> o = c.new >> >> ;-) >> >> > Actually I am very disappointed that you cannot read my mind Ara ;) it would > be quite antipols to use > not constant classnames (wouldn't be there some warnings too BTW?) Don't forget that several years ago, Matz deprecated POLS :-) (Specifically, he said "Policy of least surprise is *my* least surprise". I think it was at RubyConf 2002.) I wouldn't expect a warning just from assigning a class object to a variable. > class C... > > C=Class.new... > > works fine save for the warning I would like to get around > > Here go some ideas: > > (1) ruby does not insult you for constant redefinition if you assign a > reference to Class (arrrghh bad dangerous) > (2) allow an explicit syntax for redefining a class > (2.a) class A < B *always* redefines the class Pro: Some Gurus expect > this behavior anyway :) Not a good idea. The inheritance should be a no-op if it already exists, and an error if it's a different class. The expression "A < B" does not in any way imply that A should be undefined. You'd end up seeing: class C < Object just to trigger a redefinition. It's piggy-backing a behavior (constant redefinition) on a completely unrelated construct. > Cons: Quite implicit And arbitrary. > (2.b) new class A Pro: > Quite POLS and readable > Cons: "new" overloaded maybe use "redefine class A" > (3) some meta thingies > (3.a) const_set does not warn anymore > (3.b) Matz gives us a const_undefine for Christmas ;) > > Ok what you think? Basically I think that if you find yourself in urgent need of defining a new class using the same constant as one you've already defined, you need to review your application design :-) The warning is probably enough of a slap on the wrist to remind you of this. I do, however, think that (3.a) might be a good idea. I'm not sure, though. David -- David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org