2

For each subclass of the BaseStrategy being declared, I want to add them to the BaseStrategy.strategies array to be used later. What I can do is add class method BaseStrategy.register_strategy and call it in each subclass. But this would be error prone. Instead, I want BaseStrategy.register_strategy automatically invoked if a new subclass of BaseStrategy being declared. How can I do that?

Phương Nguyễn
  • 8,747
  • 15
  • 62
  • 96

1 Answers1

2

Use inherited hook:

class BaseStrategy
  class << self
    def inherited(klass)
      register_strategy(klass)
    end

    def register_strategy(strategy)
      puts "Adding strategy #{strategy}"
    end
  end
end

class Foo < BaseStrategy
end
Michał Młoźniak
  • 5,466
  • 2
  • 22
  • 38