Ruby on rails 嵌套模块和实例级方法
如果我有Ruby on rails 嵌套模块和实例级方法,ruby-on-rails,ruby,module,instance,Ruby On Rails,Ruby,Module,Instance,如果我有 module A include module B class C def methodC B.methodB end def self.methodD somemethod end end end module B def self.methodB A::C.methodD end end instance = A::C.new 如何避免使用此类级别的方法(self)?事实上,我如何
module A
include module B
class C
def methodC
B.methodB
end
def self.methodD
somemethod
end
end
end
module B
def self.methodB
A::C.methodD
end
end
instance = A::C.new
如何避免使用此类级别的方法(self)?事实上,我如何在
实例上调用方法b
如果我理解得很清楚,那么在某个方法中调用当前实例的关键字是self
。所以你可以用
def methodC
self.methodB
end
并在self.methodB
中删除self
(顺便说一句,除非methodD
必须出现在class C
中,否则您可以将其放入moduleB
中,然后删除methodD
;)的A::C
)尝试一下
# define moduke B first so that, it can be included in A
module B
def methodB
A::C.methodD
end
end
module A
class C
include B # include B here
def methodC
methodB
end
def self.methodD
somemethod
end
end
end
instance = A::C.new
p instance.methods.grep /methodB/
=> [:methodB]