I’m trying to create a component system in Ruby using the observer pattern. Components must be defined as modules because they exist only to be mixed in to a ComponentContainer. But there are certain methods that Components have, which I’d ideally like to define in some kind of base class, but I can’t do that since they’re modules.
Here’s what I’d like to do:
module Component
def self.on(event, &block)
#definition..
end
def self.fire(event)
#pass event to subscribers
end
end
module FooComponent < Component
on :foo_event do |param1, param2|
#...
end
end
The different types of Components use the on and fire methods, but they can’t inherit them, because modules can’t have parents. What should I do? Is this not ruby-like?
I could get this to work by making Component and FooComponent classes, but then I can’t mix them into a ComponentContainer using extend or include.
A clean way to do this is to abstract away the use of
extendusing theModule#includedhook method. This method is called on a module with a reference to the base that is including it. What this code does is creates aComponentmodule that automatically extends the base with the desired methods: