【问题标题】:Why 'self' method of module cannot become a singleton method of class?为什么模块的“自我”方法不能成为类的单例方法?
【发布时间】:2012-04-06 04:13:53
【问题描述】:
module Test
  def self.model_method
    puts "this is a module method"
  end
end

class A
  include Test
end

A.model_method

这将是错误的:

A:Class 的未定义方法 `model_method' (NoMethodError)

但是当我使用 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

谁能解释一下?

【问题讨论】:

标签: ruby


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    在您的示例中,没有可复制到 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
    

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-13
    • 2013-06-29
    • 2023-03-29
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多