Can a ruby ​​class statically track subclasses?

My goal is this:

class MyBeautifulRubyClass #some code goes here end puts MyBeautifulRubyClass.subclasses #returns 0 class SlightlyUglierClass < MyBeautifulRubyClass end puts MyBeautifulRubyClass.subclasses #returns 1 

hell is perfect even

 puts MyBeautifulRubyClass.getSubclasses #returns [SlightlyUglierClass] in class object form 

I'm sure it is possible, just not sure how!

+4
source share
2 answers

Here's an inefficient way:

See all descendants of a class in Ruby

An efficient approach would be to use hook inherited :

 class Foo def self.descendants @descendants ||= [] end def self.inherited(descendant) descendants << descendant end end class Bar < Foo; end class Zip < Foo; end Foo.descendants #=> [Bar, Zip] 

If you need to know about descendants of descendants, you can return them:

 class Foo def self.all_descendants descendants.inject([]) do |all, descendant| (all << descendant) + descendant.all_descendants end end end class Blah < Bar; end Foo.descendants #=> [Bar, Zip] Foo.all_descendants #=> [Bar, Blah, Zip] 
+9
source

Not sure if you can do this without going to ObjectSpace a la http://snippets.dzone.com/posts/show/2992 , but that can change - this is just one solution.

0
source

All Articles