问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/41527994/automatically-add-a-subclass-to-registry