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 ideally even
puts MyBeautifulRubyClass.getSubclasses #returns [SlightlyUglierClass] in class object form
I am sure this is possible, just not sure how!
Here's an inefficient way:
Look up all descendants of a class in Ruby
The efficient approach would use the inherited
hook:
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 recurse to get 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With