如何在Ruby中取消定义命名空间类?

时间:2015-05-20 11:38:49

标签: ruby

我可以取消定义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

1 个答案:

答案 0 :(得分:7)

常量在各自的父模块中定义,顶级常量在Object类上定义。

因此,ActiveRecord::BaseBase模块上定义的常量(ActiveRecord)。现在,为了删除此常量,您必须在remove_const模块上调用ActiveRecord方法:

ActiveRecord.send(:remove_const, :Base)

或者,您也可以直接从Object遍历路径,即

Object.const_get(:ActiveRecord).send(:remove_const, :Base)