【问题标题】:How to undefine namespaced class in Ruby?如何在 Ruby 中取消定义命名空间类?
【发布时间】:2015-05-20 21:36:15
【问题描述】:

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

【问题讨论】:

    标签: ruby


    【解决方案1】:

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

    因此,ActiveRecord::Base 是在ActiveRecord 模块上定义的常量(Base)。现在,为了移除这个常量,你必须在ActiveRecord 模块上调用remove_const 方法:

    ActiveRecord.send(:remove_const, :Base)
    

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

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

    【讨论】:

    • 好的,我看到它适用于 Foo::Bar,但它不适用于 ActiveRecord::Base irb(main):001:0> ActiveRecord.send(:remove_const, :Base) NameError: uninitialized constant ActiveRecord::Core::ClassMethods::Baseirb(main):002:0> Object.const_get(:ActiveRecord).send(:const_delete, :Base) NoMethodError: undefined method 'const_delete' for ActiveRecord:Module 发生这种情况是因为 ActiveRecord 未定义 :const_delete 方法吗?跨度>
    • 嗯,ActiveRecord 实际上是一个相当复杂的东西。它包括其他模块并大量使用元编程。因此,可能难以操纵。至于我的回答中的错字(const_delete),我刚刚改正了。
    猜你喜欢
    • 1970-01-01
    • 2012-07-15
    • 2013-01-08
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多