"Adelle Hartley" <adelle / bullet.net.au> schrieb im Newsbeitrag
news:courier.4242D8BE.000002FE / mars.sisgroup.com.au...
> Hi,
>
> > >
> > > If I were writing this in C++, I'd use templates.  What's
> > the Ruby Way?
> >
> > module Extension
> >   # this one is really only neede if you
> >   # want to inherit this behavior automatically
> >   # down the class hierarchy
> >   def inherited(cl)
> >     cl.extend Extension
> >   end
> >
> >   def do_my_thing(klass=self)
> >     # whatever
> >     p klass
> >   end
> > end
> >
> > >> class A
> > >>   extend Extension
> > >> end
>
> Close, but no banana.
>
> Maybe I'm not doing it right.  Here's what I've got:

You cannot use super here, because super refers to the superclass of the
class instance.  All class instances have the same super class hierarchy:

>> String.class.ancestors
=> [Class, Module, Object, Kernel]
>> Fixnum.class.ancestors
=> [Class, Module, Object, Kernel]

You need Class#superclass:

> class MyBase
>   def self.do_my_thing(klass=self)
>     p '-----'
>   end
> end
>
> module Extension
>   def inherited(cl)
>     cl.extend Extension
>   end
>
>   def do_my_thing(klass=self)
>     p klass

    superclass.do_my_thing

>   end
> end
>
> class A < MyBase
>    extend Extension
> end
>
> class B < A
> end
>
> class C < B
> end
>
> class D < C
> end
>
> D.do_my_thing
>
>
>
> My output is:
>
> D
> "-----"
>
>
> The output I want is:
>
> D
> C
> B
> A
> "-----"
>
>
> Is this possible (without repeating the definition of do_my_thing)?

And, btw, you don't need the class argument.  You can print self instead.

?> D.do_my_thing
D
C
B
A
"-----"
=> nil

Kind regards

    robert