[英]Included Module method not found in class in Ruby
I'm getting no method found error for my module methods. 我的模块方法没有找到方法错误。 They are defined like so: 它们的定义如下:
module MyModule
def my_method
"stuff"
end
end
And the class is like this: 这个类是这样的:
class MyClass
include MyModule
def self.do_stuff
my_method
end
end
Then I'm trying to call it like so: 然后我试图这样称呼它:
MyClass.do_stuff
I'm getting 我越来越
undefined method 'my_method" for MyClass:Class
I have also tried 我也尝试过
self.my_method
in the Module, but no luck. 在模块中,但没有运气。 I should mention this is a vanilla ruby class within a rails application. 我应该提到这是Rails应用程序中的香草红宝石类。 application.rb includes the following line application.rb包含以下行
config.autoload_paths += %W(#{config.root}/lib)
and in the console I can verify that the module is getting loaded. 在控制台中,我可以验证模块是否已加载。 Any ideas on this? 有什么想法吗? Thanks 谢谢
you want to use extend to make the method a class method. 您想使用扩展使方法成为类方法。
class MyClass
extend MyModule
def self.do_stuff
my_method
end
end
Define functions in module as module_function
and it should work. 在模块module_function
函数定义为module_function
,它应该可以工作。
module MyModule
module_function
def my_method
"stuff"
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.