我可以取消定义Bar(How to undefine class in Ruby?),但是如何取消定义Foo :: Bar?
irb(main):266:0> Object.send :remove_const, :ActiveRecord::Base
TypeError: :ActiveRecord is not a class/module
irb(main):267:0> Object.send :remove_const, :"ActiveRecord::Base"
NameError: `ActiveRecord::Base' is not allowed as a constant name
irb(main):269:0> module ActiveRecord; Object.send :remove_const, :Base; end
NameError: constant Object::Base not defined
答案 0 :(得分:7)
常量在各自的父模块中定义,顶级常量在Object
类上定义。
因此,ActiveRecord::Base
是Base
模块上定义的常量(ActiveRecord
)。现在,为了删除此常量,您必须在remove_const
模块上调用ActiveRecord
方法:
ActiveRecord.send(:remove_const, :Base)
或者,您也可以直接从Object
遍历路径,即
Object.const_get(:ActiveRecord).send(:remove_const, :Base)