微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

红宝石 – 为什么“自我”模块的方法不能成为类的单例方法?

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

class A
  include Test
end

A.model_method

这将是错误的:

undefined method `model_method’ for A:Class (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

有人可以解释一下吗

解决方法

如果要在包含模块时将类方法和实例方法混合到一个类中,则可以按照以下模式:
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

基本上要过度简化它,你扩展到添加方法,并包括添加实例方法.当包含模块时,#included方法调用,其中包含实际的类.从这里可以使用另一个模块的一些类方法来扩展类.这是一个很常见的模式.

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

原文地址:https://www.jb51.cc/ruby/274135.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐