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. The basic Class looks like this:
我有一个小问题,我无法理解。由于我想重用我的类中定义的许多方法,我决定将它们放入Helper中,我可以随时轻松地将其包含在内。基本类看起来像这样:
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? What am I doing wrong?
现在我不能从我的班级调用“helper_method”因为我认为是范围问题?我究竟做错了什么?
1 个解决方案
#1
0
I guess that is because self
pointer inside of do_something input
is InternshipInputFormatter
, and not the instance of 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:
我想这是因为do_something输入中的自指针是InternshipInputFormatter,而不是InternshipInputFormatter的实例。所以调用helper_method(输入)的正确别名将是self.helper_method(输入),但是你已经将Helper :: MyHelper作为实例方法包含在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
. Please refer to the document to see the detailed difference between include
, and extend
.
如您所见,调用已停止helper_method内的执行。请参阅文档以查看include和extend之间的详细区别。
#1
0
I guess that is because self
pointer inside of do_something input
is InternshipInputFormatter
, and not the instance of 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:
我想这是因为do_something输入中的自指针是InternshipInputFormatter,而不是InternshipInputFormatter的实例。所以调用helper_method(输入)的正确别名将是self.helper_method(输入),但是你已经将Helper :: MyHelper作为实例方法包含在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
. Please refer to the document to see the detailed difference between include
, and extend
.
如您所见,调用已停止helper_method内的执行。请参阅文档以查看include和extend之间的详细区别。