I would like to put some code in module that throws an error if certain method is not defined.
This module relies on the external definition of this method, since this method’s implementation is different for all classes. This code would help developers know early that they forgot to implement the method rather than when they tried to use features of the module.
module MyModule
def self.included(klass)
raise "MyModule: please `def my_method` on #{klass}" unless klass.respond_to?(:my_method)
end
end
I can easily raise an error in a module’s included definition if a method is not defined, however since most modules are included at the top of a file, it’s likely that my required method is defined in the class, but not before my module is included.
class MyClass
include MyModule
def self.my_method
# ...
end
end
This would still raise an error 🙁
Is it possible to raise an error only if the method truly is not defined in the class definition? Almost need a class.onload callback of sorts. If not, any other ideas for how to mitigate the possibilities that a programmer might include our module without defining this needed method?
Sounds like you want to make use of
method_missinganddefine_method.If you do use
method_missingdon’t forget to:superfor unhandled cases.respond_to?methodlook at this question, plus this and that.
Update:
It sounds the goal is to do static method checking like Java or c++ does. This is not really meaningful in ruby 🙁
Since in ruby:
Foodoes not have a method at class load time is meaningless.With regards to “class on load”: A class definition is really executed. Try this:
You will see “Hi” the first and only the first time Foo is used. This is how things like devise hook into do their magic.
So maybe by private convention have developers add a
check_classmethod call to the bottom of the classes in question?I understand the intent but it seems like fighting the way ruby is designed to work.
As a mostly Java person I appreciate the frustration. Let me guess: repeated cases of code getting pushed to production that had missing methods? 😛
Update2:
wrt
onloadIn ruby barring use of frozen a class get new methods defined all the time. ( Or an instance can get new methods defined just for that instance. ) so checking for a method’s nonexistence is only a snapshot check and not as definitive a check as a static language brings to the table. This is ruby’s very own Halting problem