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

时间:2013-01-11 15:13:03

标签: ruby

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

2 个答案:

答案 0 :(得分:4)

一个常见的习语是:

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"

InstanceMethods模块有什么用?

当我需要模块在我的类中包含实例和类方法时,我使用了两个子模块。通过这种方式,方法可以整齐地分组,例如,可以在代码编辑器中轻松折叠。

它也感觉更“均匀”:两种方法都是从self.included钩子注入的。

无论如何,这是个人偏好的问题。此代码的工作原理完全相同:

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

答案 1 :(得分:2)

简短的回答是:不,你不能使模块对象本身的方法(模块的“类”方法)在另一个对象的继承链中。 @ Sergio的答案是一个常见的解决方法(通过将“类”方法定义为另一个模块的一部分)。

您可能会发现以下图表具有指导性(点击查看完整尺寸或get the PDF):

Ruby Method Lookup Flow http://phrogz.net/RubyLibs/RubyMethodLookupFlow.png

注意:此图尚未针对Ruby 1.9进行更新,其中还有其他核心对象,如BasicObject,稍微改变了根流。 < / p>

相关问题