Hi, I'm Benedikt Deicke, and I'm a freelance web and software developer. I'm mainly building user focused web applications using Ruby on Rails and JavaScript. Additionally I'm currently studying for my master's degree and enjoying photography in my spare time. Feel free to get in touch with me, I'm available for hire!

July 10th, 2007
Getting a class' subclasses

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. (Already confused by all the classes? ;-))

   1  class Strategy
   2    @@subclasses = Array.new
   3    class << self
   4      def inherited(klass)
   5         @@subclasses << klass
   6      end
   7  
   8      def subclasses
   9        @@subclasses.join(', ')
  10      end
  11    end
  12  end

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

   1  class StrategyA < Strategy; end
   2  class StrategyB < Strategy; end
   3  class StrategyC < Strategy; end
   4  
   5  # Let's get the current list of subclasses
   6  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.

Posted by benediktFiled in Articles, Ruby
Bookmark and Share

Sorry, comments are closed for this article.