如何在Ruby中取消名称空间类的定义?
我可以取消对Bar()的定义,但是如何取消对Foo::Bar的定义呢如何在Ruby中取消名称空间类的定义?,ruby,Ruby,我可以取消对Bar()的定义,但是如何取消对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'
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
常量在各自的父模块中定义,顶级常量在
对象
类中定义
因此,ActiveRecord::Base
是在ActiveRecord
模块上定义的常量(Base
)。现在,要删除此常量,必须调用ActiveRecord
模块上的remove\u const
方法:
ActiveRecord.send(:remove_const, :Base)
或者,您也可以直接从对象
遍历路径,即
Object.const_get(:ActiveRecord).send(:remove_const, :Base)
好的,我看到它适用于Foo::Bar,但不适用于ActiveRecord::Base
irb(main):001:0>ActiveRecord.send(:remove_const,:Base)name错误:未初始化常量ActiveRecord::Core::ClassMethods::Base
或irb(main):002:0>对象。const_get(:ActiveRecord)。send(:const_delete,:Base)NoMethodError:ActiveRecord:Module的未定义方法“const_delete”是否因为ActiveRecord未定义:const_delete方法而发生这种情况?实际上,ActiveRecord是一件相当复杂的事情。它包括其他模块,大量使用元编程。因此,它可能很难操纵。至于我答案中的打字错误(const_delete
),我只是修正了它。