【问题标题】:Include 2 modules with the same methods包含 2 个具有相同方法的模块
【发布时间】: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

由于某种原因ModuleAModuleB 具有相同的逻辑(方法),但方法的实现不同。因此,我需要将它们放在单独的文件(模块)中以便于重构,因为我需要经常更改方法的实现。现在,我在不同的模块中使用不同的方法名称(前缀)。

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 中使用相同的方法名称(methodother_method)从 ModuleB 运行 other_method,我会收到错误。

模块中是否可以有相同的方法名称?我需要如何命名它们,以使 method 从实现它的同一模块运行 other_method

感谢您的帮助!

【问题讨论】:

  • 你遇到了什么错误?
  • 模块在他们的实现中使用了 Nokogiri,所以当 method 来自 ModuleA 运行 other_method 来自 ModuleB 时,我得到了 Nokogiri 错误。在每个模块中,大约有 10 种方法,它们相互连接。因此,我得到的错误是在模块实现中,当来自不同模块的方法相互混合时。当所有方法在一个 Module 中运行时,没有错误。因此,某个错误消息无法帮助您回答我的问题,这不是因为模块实现,而是因为方法混合。

标签: ruby-on-rails ruby module


【解决方案1】:

不理想取决于您的模块的大小,但是 not 包括它们呢?像这样的:

class SomeController < ApplicationController
  def index
    module = something? ? ModuleA : ModuleB
    module.method
  end
end

【讨论】:

    猜你喜欢
    • 2018-12-21
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 2011-05-06
    • 1970-01-01
    • 2019-12-12
    相关资源
    最近更新 更多