How to enumerate nested classes

T

Tim Hunter

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?
 
J

Joel VanderWerf

Tim said:
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)
 
T

Tim Hunter

Joel said:
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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top