James Harrod
James Harrod

Reputation: 3

How can I write derived Ruby classes that call a base class's method when they're defined?

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

Answers (1)

numbers1311407
numbers1311407

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

Related Questions