[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

extend(Module) and inheritance

Patrick Gundlach

6/11/2005 2:10:00 PM

Hi out there,

I would like to extend an object with a module. That is no problem so
far, but I have an Class hierarchy where each module is split like
this:

--------------------------------------------------
class A
def bar; "bar" ; end

module WithDash
def bar ; "-bar-" ; end
end
end

class B < A
def foo ; "foo"; end

module WithDash
def foo ; "-foo-" ; end
end
end
--------------------------------------------------

My goal is to extend an object of B with module B::WithDash so that
the object is automatically extended with module A::WithDash as well.
Or any equivalent. Perhaps I should use something like

(x.class.ancestors - [Object,Kernel]).each { |klass|
x.extend(klass::WithDash)
}
??

With the definition of A and B above, I'd like to use something
similar to the first "extend" in this example and have both methods
use the WithDash variant:
--------------------------------------------------
b = B.new

b.extend(B::WithDash)
p b.foo # should be both with a dash
p b.bar # (this one, of course, isn't)

# this will do, but I don't want to know the superclasses of B
b.extend(A::WithDash)
p b.foo # print both with a dash
p b.bar #
--------------------------------------------------

Thanks,

Patrick
2 Answers

nobu.nokada

6/11/2005 3:26:00 PM

0

Hi,

At Sun, 12 Jun 2005 00:05:52 +0900,
Patrick Gundlach wrote in [ruby-talk:145161]:
> class B < A
> def foo ; "foo"; end
>
> module WithDash
include A::WithDash
> def foo ; "-foo-" ; end
> end
> end

--
Nobu Nakada


Patrick Gundlach

6/11/2005 4:05:00 PM

0

Hi,

>> class B < A
>> def foo ; "foo"; end
>>
>> module WithDash
> include A::WithDash

Yeah! Thats it.

Thank you,


Patrick