加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:48:40 所属栏目:百科 来源:网络整理
导读:module Test def self.model_method puts "this is a module method" endendclass A include TestendA.model_method 这将是错误的: undefined method `model_method’ for A:Class (NoMethodError) 但是当我使用A的元类时,它的作用是: module Test def mod
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读