Reputation: 3
Let's say I have this class:
class ComponentLibrary
def self.register(klass); ...; end
end
And suppose I also have this base class:
class BaseComponent
ComponentLibrary.register self
end
How can I write derivative classes, with a minimum of repetition, that will register themselves with ComponentLibrary
when they're defined? (In other words, I'd prefer not to keep writing ComponentLibrary.register self
everywhere.)
Just to be clear, I'm talking about writing other classes like:
class RedComponent < BaseComponent
# ...
end
class BlueComponent < BaseComponent
# ...
end
but I don't want to write ComponentLibrary.register self
for each one.
Upvotes: 0
Views: 416
Reputation: 34072
class BaseComponent
def self.inherited(base)
ComponentLibrary.register(base)
end
end
class RedComponent < BaseComponent
end
Something along these lines might work for you.
Edit: changed to #inherited.
Upvotes: 3