Object.module_eval do
# Unset a constant without private access.
def self.const_unset(const)
self.instance_eval { remove_const(const) }
end
end
或者,您可以让Ruby解释器闭嘴(这会抑制 * 所有 * 警告):
# Runs a block of code without warnings.
def silence_warnings(&block)
warn_level = $VERBOSE
$VERBOSE = nil
result = block.call
$VERBOSE = warn_level
result
end
require 'clashing_library'
some_class_alias = SomeClass
SomeClass = nil
# You can now define your own class:
class SomeClass; end
# Or your own constant:
SomeClass = 'foo'
5条答案
按热度按时间wsxa1bj11#
问题的解决方案取决于问题的原因。
1 -您正在更改之前在代码中某个位置设置的常量的值,或者试图定义与现有类或模块同名的常量。解决方案:如果你事先知道常量的值会改变,就不要使用常量;不要定义与类/模块同名的常量。
2 -你正处于一种情况下,你想重新定义一个常量有很好的理由,没有得到警告,有两个选择。
首先,可以在重新定义常量之前取消定义它(这需要一个helper方法,因为
remove_const
是一个私有函数):或者,您可以让Ruby解释器闭嘴(这会抑制 * 所有 * 警告):
3 -您需要一个外部库来定义一个名称与您正在创建的新常量或类/模块冲突的类/模块。将代码 Package 在顶级模块名称空间中以防止名称冲突。
型
4 -和上面一样,但是你绝对需要定义一个和gem/库的类同名的类。你可以把库的类名赋给一个变量,然后清除它以备以后用途:
rks48beu2#
试试这个:
qncylg1j3#
要禁止显示警告,请在脚本顶部使用以下代码:
8yparm6h4#
this question的公认答案是有帮助的。我查看了Rails源代码,得到了以下内容。在加载文件之前和之后,我可以插入以下行:
rur96b6h5#
使用user2398029's reply,我删除警告的最简单方法是添加以下行: