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

ruby-on-rails – 是否可以反转一个类中包含的模块?

发布时间:2020-12-16 22:36:25 所属栏目:百科 来源:网络整理
导读:您可以将类中的模块包含在类中,以将类方法和实例方法添加到该特定类来扩展类功能. module M def self.class_method_from_module 'from class_method_from_module' end def instance_method_from_module 'from instance_method_from_module' endendclass C in
您可以将类中的模块包含在类中,以将类方法和实例方法添加到该特定类来扩展类功能.
module M
 def self.class_method_from_module
  'from class_method_from_module'
 end

 def instance_method_from_module
  'from instance_method_from_module'
 end
end

class C
 include M

 def self.class_method
  'from class_method'
 end

 def instance_method
  'from instance_method'
 end
end

puts C.class_method => 'from class_method'

puts C.class_method_from_module => 'from class_method_from_module'

puts C.new.instance_method => 'from instance_method'

puts C.new.instance_method_from_module => 'instance_method_from_module'

现在即使从存储器中删除模块M,具体如下:

Object.send(:remove_const,:M) #remove the module M

puts C.class_method_from_module => 'from class_method_from_module'

puts C.new.instance_method_from_module => 'instance_method_from_module'

而不是缺少方法.这是为什么?什么是删除模块添加到类的功能的最佳方法?

解决方法

细节因实现而异,但是我知道至少在JRuby和MRI 1.8中,当扩展或包含模块时,有一个称为Include Class的构造,它被插入到一个类的继承链中.因此,模块不会被垃圾收集,因为Include类仍然引用它,并且方法仍将在你的类上.帕特里克·法利(Patrick Farley)在 his blog发表了有关这个和相关主题的一些精彩文章.

因此,要“删除”一个模块,您可以单独取消定义模块中的每个方法,但这是一个非常笨重的机制.如果使用宝石是可以接受的,那么使用专门为了动态添加和删除模块而设计的Mixology可能会更好.

(编辑:李大同)

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

    推荐文章
      热点阅读