I have the following piece of code. It is actually three separate scripts except I combined it together. The Main class is something the two Test classes inherit. They may define an out method, which will do whatever the devs want. This is meant to be a plugin-style sort of design so that people can define their own out methods in their own classes, and then when my main program picks up one of those custom classes I can just say
some_test.run
And if they decided to implement an out method that will be executed.
Is there a better way to implement the run method so that I don’t need to explicitly write self.class.method_defined?? The object could be any Test object and I don’t want them to have to overwrite the run method to put their own class name in front of the method_defined? call.
class Main
def run
send(:out) if self.class.method_defined?(:out)
end
end
class TestA < Main
def out
p "Test A here"
end
end
class TestB < Main
def out
p "Test B here"
end
end
a = TestA.new
a.run
# will execute a's out method
b = TestB.new
b.run
# will execute b's out method
I would just provide an empty
outmethod in the parent class and allow subclasses to override it, just normal OO:You could also just use
defined?:Note the argument to
definedisout, not the symbol:out.Or, more idiomatically, you can use
respond_to?: