Christopher Dicely
3/6/2008 3:57:00 PM
On Wed, Mar 5, 2008 at 4:19 PM, Chirag Patel <patelc75@yahoo.com> wrote:
> I would like to create a new superclass 'Super' for an existing class
> 'Sub'
>
> class Sub
> def new
> #do something second
> end
> end
>
> class Super < Sub
> def new
> #do something first
> end
> end
Note that this makes Sub a superclass of Super (Super inherits from
Sub), not the
other way around. I don't know if you can change the superclass of a class at
runtime, because Ruby uses single inheritance and Sub already has an parent
(Object). You can make a module, but AFAIK not a class even though a class is a
module, a "superclass" by including it.
> Is it possible create this new Super class so that Super::new is called
> every time Sub:new is called without modifying Sub?
No, but since Ruby has open classes, its pretty easy to modify sub so
that Super::initialize (what you probably really want) is called whenever
Sub::initialize is called (either before or after Sub::initialize executes).
>
> The is because Sub already exists and I don't want to tamper the code.
You don't have to modify the code of that you are getting Sub from to
modify its behavior.
> Basically I have a bunch of existing classes that I want to inherit from
> 'Super' so that I can include some error handling in 'Super'. Is there
> another better way to accomplish this without modifying the existing
> subclasses?
The best way is probably to create a module that does what you want,
and reopen the existing classes and include that module in each of them.