如何在 class 中包含模块

How to include a module in a class

我 gem 中的一个模块包含在另一个 gem 中的 class 中,后者由 Rails 应用程序中的自定义 class 扩展:

我的gem:

module MyGem
    def my_method
    end
end
AnotherGem.send :include, MyGem

另一个gem:

class AnotherGem
end

Class 在 Rails 应用中:

class ClassInRailsApp < AnotherGem
end

运行 这会导致以下行为:

$ rails c
Loading development environment (Rails 5.1.4)
irb(main):004:0> MyGem.method_defined? :my_method
=> true
irb(main):005:0> AnotherGem.method_defined? :my_method
=> true
irb(main):006:0> ClassInRailsApp.method_defined? :my_method
NoMethodError: undefined method `my_method' for ClassInRailsApp:Class

如何确保在扩展 class 之前包含我的模块?

编辑:

我试过在ClassInRailsApp中直接包含MyGem,指定的实例方法还是不可用。问题可能与此有关吗?

按照你的想法,你只是在调用一个方法,例如@object.my_method。实际上,您正在调用 Class 级别方法,例如Object.my_method,但将其定义为实例级方法。执行您正在尝试的操作的正确方法是 Object.new.my_method,但是,不要那样做。

要调用这样的方法,您必须将其定义为 class 上的方法。请参阅 this page,以获得更好的理解。具体来说,"A Common Idiom" 部分介绍了如何通过模块定义 Class 级别的方法。