Menu

Published by
Categories: Ruby

I needed a way to get a list of the subclasses that inherit a specific. Unfortunately there is no method like Class.subclasses (there is Class.superclass, though) so I had to look for another way to achieve this. Let’s say, we want to have an array containing all subclasses as a class variable of our superclass Strategy. In order to fill the array we’ll overwrite the inherited class method of Class.

class Strategy
  @subclasses = Array.new
  class << self
    def inherited(klass)
       @subclasses << klass
    end

    def subclasses
      @subclasses.join(', ')
    end
  end
end

Now, every time a class extends Strategy our new inherited method is called and adds the class to our array.

class StrategyA < Strategy; end
class StrategyB < Strategy; end
class StrategyC < Strategy; end

# Let's get the current list of subclasses
puts Strategy.subclasses # will output StrategyA, StrategyB, StrategyC

What happens if a class inherits any of our subclasses? Well, as long as you don’t overwrite the inherited method again it’s also added to the array.

Cover medium

Learn how to build SaaS applications!

I’m writing a book on building SaaS applications using Ruby on Rails. Sign up now to get a sneak peek at the outline, and an exclusive discount when it’s ready.

Thanks for checking by, mate! You're already signed up to be notified about the release of the SaaS Guidebook. In the meantime, why don't you check out the current outline of the book?

Download the outline