代码之家  ›  专栏  ›  技术社区  ›  B Seven

当一个模块中定义的方法都包含在Ruby的一个类中时,如何从另一个模块调用它们?

  •  -1
  • B Seven  · 技术社区  · 6 年前
    module A
      def before
        puts :before
      end
    end
    
    module B
      before
    end
    
    class Test
      include A
      include B
    end
    

    所以,我们的目标是 before 在分析模块B时,不使用 extend A 在模块B内。

    红宝石2.5.1

    1 回复  |  直到 6 年前
        1
  •  0
  •   max pleaner    6 年前

    当你 include 获取模块的实例方法并将其作为实例方法导入的模块。然而,你称之为 before 这里的方法只有在 方法。

    如果你想让B导入 之前 作为类方法,可以使用 extend 以下内容:

    module B
      extend A
      before
    end
    

    延伸 ,你可以打电话 之前 仅在实例方法作用域中从B调用,并且仅当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