[英]Using methods defined in a module with class methods in Ruby
I have a small problem that I can't quite get my head around. 我有一个小问题,我无法完全解决。 Since I want to reuse a lot of the methods defined in my Class i decided to put them into an Helper, which I can easily include whenever needed.
由于我想重用我的课堂中定义的许多方法,因此我决定将它们放入一个Helper中,可以在需要时轻松地将其包括在内。 The basic Class looks like this:
基本类如下所示:
class MyClass
include Helper::MyHelper
def self.do_something input
helper_method(input)
end
end
And here is the Helper: 这是助手:
module Helper
module MyHelper
def helper_method input
input.titleize
end
end
end
Right now I can't call "helper_method" from my Class because of what I think is a scope issue? 现在,由于我认为范围问题,我无法从我的班级中调用“ helper_method”? What am I doing wrong?
我究竟做错了什么?
I guess that is because self
pointer inside of do_something input
is InternshipInputFormatter
, and not the instance of InternshipInputFormatter
. 我猜这是因为
do_something input
内部的self
指针是InternshipInputFormatter
,而不是InternshipInputFormatter
的实例。 so proper alias to call helper_method(input)
will be self.helper_method(input)
, however you have included the Helper::MyHelper
into the InternshipInputFormatter
class as an instance methods, not a singleton, so try to extend the class with the instance methods of the module as the signelton methods for the class: 因此,调用
helper_method(input)
适当别名将是self.helper_method(input)
,但是您已经将Helper::MyHelper
作为实例方法(而不是单例self.helper_method(input)
包含在InternshipInputFormatter
类中,因此请尝试使用实例方法扩展该类。作为该类的signelton方法的模块:
class InternshipInputFormatter
extend Helper::MyHelper
def self.do_something input
helper_method(input)
end
end
InternshipInputFormatter.do_something 1
# NoMethodError: undefined method `titleize' for 1:Fixnum
As you can see, the call has stopped the execution inside the helper_method
. 如您所见,该调用已停止了
helper_method
内部的执行。 Please refer to the document to see the detailed difference between include
, and extend
. 请参考文档以了解
include
和extend
之间的详细区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.