简体   繁体   English

如何将另一个模块的类方法导入我的ruby类/模块?

[英]How do I import another module's class methods into my ruby class/module?

我知道我可以导入instance_methods,但是可以导入类方法吗?如何导入?

A common idiom is this: 一个常见的成语是:

module Bar
  # object model hook. It's called when module is included. 
  # Use it to also bring class methods in by calling `extend`.
  def self.included base
    base.send :include, InstanceMethods
    base.extend ClassMethods
  end

  module InstanceMethods
    def hello
      "hello from instance method"
    end
  end

  module ClassMethods
    def hello
      "hello from class method"
    end
  end
end

class Foo
  include Bar
end

Foo.hello # => "hello from class method"
Foo.new.hello # => "hello from instance method"

What's with that InstanceMethods module? 那个InstanceMethods模块是什么?

When I need module to include both instance and class methods to my class, I use two submodules. 当我需要将实例方法和类方法都包括在类中的模块时,我使用两个子模块。 This way the methods are neatly grouped and, for example, can be easily collapsed in code editor. 这样,方法可以被整齐地分组,例如,可以在代码编辑器中轻松折叠。

It also feels more "uniform": both kinds of methods are injected from self.included hook. 还感觉更“统一”:两种方法都是从self.included钩子中注入的。

Anyway, it's a matter of personal preference. 无论如何,这是个人喜好问题。 This code works exactly the same way: 这段代码的工作方式完全相同:

module Bar
  def self.included base
    base.extend ClassMethods
  end

  def hello
    "hello from instance method"
  end

  module ClassMethods
    def hello
      "hello from class method"
    end
  end
end

The short answer is: no, you cannot cause methods of the module object itself ("class" methods of the module) to be in the inheritance chain for another object. 简短的答案是:不,您不能使模块对象本身的方法(模块的“类”方法)位于另一个对象的继承链中。 @Sergio's answer is a common workaround (by defining the "class" methods to be part of another module). @Sergio的答案是一种常见的解决方法(通过将“类”方法定义为另一个模块的一部分)。

You may find the following diagram instructive (click for full-size or get the PDF ): 您可能会发现以下图表具有指导意义(单击以查看大图或获取PDF ):

Ruby方法查找流程
(source: phrogz.net ) (来源: phrogz.net

Note: this diagram has not yet been updated for Ruby 1.9, where there are additional core objects like BasicObject that slightly change the root flow. 注意:此图尚未针对Ruby 1.9进行过更新,在Ruby 1.9中,还有一些其他核心对象(如BasicObject会稍微改变根流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM