Given the following Interface in a module:
module Action
abstract def perform
end
I would like to use it to instantiate different classes that implement it:
class Run
include Action
def perform
puts "run!"
end
end
class Jump
include Action
def perform
puts "jump!"
end
end
I know is possible to define an array like [] of Action
and be able to store instances of Action
, but I'm interested on the classes instead of the instances.
I would like to know how to define the type restriction so I can store a reference to the class that implements the interface and not an specific instance.
My objective is be able to instantiate a fresh instance of certain class and be able to invoke the perform
method in it.
At this time it is possible to write the following code:
actions = [Run, Jump]
actions.each do |klass|
instance = klass.new.as(Action)
instance.perform
end
And things will work, however it will not be possible to store that list of classes into a instance variable since the type restrictions are a bit more strict.
What would be the type restriction syntax for that case?
The first idea that comes to mind is using
[] of Action.class
, but that doesn't work. Maybe that should work, but it will need a change/enhancement in the compiler.In the meantime you can do this: