[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

How to enumerate nested classes

Tim Hunter

11/4/2004 10:14:00 PM

I have a class nested in a module:

module Foo
class Bar
... buncha stuff here
end
end

Within Foo::Bar there are many nested classes, not necessarily descended
from Bar, simply contained within its namespace.

I would like to write a test that ensures that each class contained within
Foo::Bar has a method named deep_copy() somewhere in its inheritence
hierarchy. I'd like to write the test without explicitly listing all the
nested classes. That is, if I add another class to Foo::Bar, then the test
automatically checks it as well.

I thought I could do this via ObjectSpace.each_object(Foo::Bar) but that
doesn't work. I also tried getting a list of Foo::Bar's constants and going
from there but I got nowhere.

Any ideas?
2 Answers

Joel VanderWerf

11/4/2004 11:22:00 PM

0

Tim Hunter wrote:
> I have a class nested in a module:
>
> module Foo
> class Bar
> ... buncha stuff here
> end
> end
>
> Within Foo::Bar there are many nested classes, not necessarily descended
> from Bar, simply contained within its namespace.
>
> I would like to write a test that ensures that each class contained within
> Foo::Bar has a method named deep_copy() somewhere in its inheritence
> hierarchy. I'd like to write the test without explicitly listing all the
> nested classes. That is, if I add another class to Foo::Bar, then the test
> automatically checks it as well.
>
> I thought I could do this via ObjectSpace.each_object(Foo::Bar) but that
> doesn't work. I also tried getting a list of Foo::Bar's constants and going
> from there but I got nowhere.
>
> Any ideas?

You were on the right track:

module Foo
class D; end
class Bar
class C1; end
class C2; end
K = 3
end
end

p Foo::Bar.constants.map{|k|Foo::Bar.const_get(k)}.grep(Class)


Tim Hunter

11/5/2004 12:14:00 AM

0

Joel VanderWerf wrote:
>
> p Foo::Bar.constants.map{|k|Foo::Bar.const_get(k)}.grep(Class)

Excellent! Not only did this pretty much work right out of the box, I found
two classes that didn't have a deep_copy() method! Thanks!