【问题标题】:How to call a method defined in one module from another module when they are both included in a class in Ruby?当它们都包含在Ruby中的一个类中时,如何从另一个模块中调用一个模块中定义的方法?
【发布时间】:2018-11-02 21:31:53
【问题描述】:
module A
  def before
    puts :before
  end
end

module B
  before
end

class Test
  include A
  include B
end

因此,目标是在解析模块 B 时调用 before,而不在模块 B 中使用 extend A

Ruby 2.5.1

【问题讨论】:

  • 如果您在module A 中定义为self.before 并在module B 中调用A::before 对您来说是否有效?
  • “解析模块 B”——此时,它没有机会知道 before 应该解析为 A。因此,鉴于当前的定义/限制,这是不可能的。
  • 您能否详细说明您要达到的目标?也许还有另一种方法可以做到这一点
  • 解析期间不能执行代码。 Ruby 没有解析时代码执行,例如Lisp 有。
  • @LeticiaEsperon - 为路由器创建前置过滤器。

标签: ruby mixins


【解决方案1】:

当您include 一个模块时,它采用模块的实例方法并将它们作为实例方法导入。但是,您在此处调用 before 方法的方式仅适用于 class 方法。

如果您希望 B 将 before 作为类方法导入,您可以使用 extend 来实现:

module B
  extend A
  before
end

没有这个额外的extend,你只能在实例方法范围内从B调用before,并且只有当B上的方法被Test调用时:

module A
  def before
    puts :before
  end
end

module B
  def call_before
    before
  end
end

class Test
  include A
  include B
  def do_thing
    call_before
  end
end

Test.new.do_thing # => before

【讨论】:

    猜你喜欢
    • 2020-04-17
    • 1970-01-01
    • 2020-04-17
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多