【发布时间】:2017-07-03 02:42:30
【问题描述】:
我有一个Controller,现在包括两个Modules。
class SomeController < ApplicationController
include ModuleA
include ModuleB
def index
if something?
a_method # Method from ModuleA
else
b_method # Method from ModuleB
end
end
end
由于某种原因ModuleA 和ModuleB 具有相同的逻辑(方法),但方法的实现不同。因此,我需要将它们放在单独的文件(模块)中以便于重构,因为我需要经常更改方法的实现。现在,我在不同的模块中使用不同的方法名称(前缀)。
module ModuleA
def a_method
a_other_method
...
end
private
def a_other_method
...
end
end
module ModuleB
def b_method
b_other_method
...
end
private
def b_other_method
...
end
end
如果我在 ModuleA 的两个模块 method 中使用相同的方法名称(method 和 other_method)从 ModuleB 运行 other_method,我会收到错误。
模块中是否可以有相同的方法名称?我需要如何命名它们,以使 method 从实现它的同一模块运行 other_method?
感谢您的帮助!
【问题讨论】:
-
你遇到了什么错误?
-
模块在他们的实现中使用了 Nokogiri,所以当
method来自ModuleA运行other_method来自ModuleB时,我得到了 Nokogiri 错误。在每个模块中,大约有 10 种方法,它们相互连接。因此,我得到的错误是在模块实现中,当来自不同模块的方法相互混合时。当所有方法在一个 Module 中运行时,没有错误。因此,某个错误消息无法帮助您回答我的问题,这不是因为模块实现,而是因为方法混合。
标签: ruby-on-rails ruby module