18
module Test
  def self.model_method
    puts "this is a module method"
  end
end

class A
  include Test
end

A.model_method

这将是错误的:

A:Class (NoMethodError) 的未定义方法“model_method”

但是当我使用 A 的元类时,它可以工作:

module Test
  def model_method
    puts "this is a module method"
  end
end

class A
  class << self
    include Test
  end
end

A.model_method

有人可以解释一下吗?

4

2 回答 2

34

如果您希望在包含模块时将类方法和实例方法混合到一个类中,您可以遵循以下模式:

module YourModule
  module ClassMethods
    def a_class_method
      puts "I'm a class method"
    end
  end

  def an_instance_method
    puts "I'm an instance method"
  end

  def self.included(base)
    base.extend ClassMethods
  end
end

class Whatever
  include YourModule
end

Whatever.a_class_method
# => I'm a class method

Whatever.new.an_instance_method
# => I'm an instance method

基本上为了过度简化它,您extend添加类方法并include添加实例方法。当一个模块被包含时,它的#included方法被调用,它被包含在实际的类中。从这里你可以extend使用来自另一个模块的一些类方法的类。这是很常见的模式。

另见:http ://api.rubyonrails.org/classes/ActiveSupport/Concern.html

于 2012-04-06T05:20:42.857 回答
11

包含一个模块类似于复制其实例方法。

在您的示例中,没有实例方法可以复制到A. model_method实际上是Test的单例类的实例方法。


鉴于:

module A
  def method
  end
end

这:

module B
  include A
end

与此类似:

module B
  def method
  end
end

当你这样想的时候,这是完全有道理的:

module B
  class << self
    include A
  end
end

B.method

在这里,方法被复制到B模块的单例类中,这使它们成为B.

请注意,这与以下内容完全相同:

module B
  extend A
end

实际上,这些方法并没有被复制。没有重复。该模块只是包含在方法查找列表中。

于 2012-04-06T04:47:06.040 回答