Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a ruby class statically keep track of subclasses?

Tags:

ruby

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!

like image 617
A Question Asker Avatar asked Jan 19 '23 12:01

A Question Asker


1 Answers

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]
like image 59
d11wtq Avatar answered Jan 30 '23 13:01

d11wtq