如何在加载文件时禁用重新定义常量的警告

时间:2012-02-10 23:25:22

标签: ruby warnings constants suppress-warnings

有没有办法在加载特定文件时禁用warning: already initialized constant

4 个答案:

答案 0 :(得分:42)

问题的解决方案取决于导致问题的原因。

1 - 您正在更改在代码中某处之前设置的常量的值,或者正在尝试定义与现有类或模块同名的常量。解决方案:如果事先知道常量的值会改变,请不要使用常量;不要定义与类/模块同名的常量。

2 - 您处于这样一种情况,即您希望在没有收到警告的情况下重新定义常量。有两种选择。

首先,您可以在重新定义之前取消定义常量(这需要辅助方法,因为remove_const是私有函数):

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

3 - 您需要一个外部库来定义一个类/模块,其名称与您正在创建的新常量或类/模块相冲突。解决方案:将代码包装在顶级模块命名空间中以防止名称冲突。

class SomeClass; end
module SomeModule
   SomeClass = '...' 
end

4 - 与上面相同,但您绝对需要定义一个与gem / library类同名的类。解决方案:您可以将库的类名分配给变量,然后将其清除以供以后使用:

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'

答案 1 :(得分:21)

试试这个:

Kernel::silence_warnings { MY_CONSTANT = 'my value '}

答案 2 :(得分:12)

this question接受的答案很有帮助。我查看了Rails源代码以获得以下内容。在加载文件之前和之后,我可以插入这些行:

# Supress warning messages.
original_verbose, $VERBOSE = $VERBOSE, nil
    load(file_in_question)
# Activate warning messages again.
$VERBOSE = original_verbose

答案 3 :(得分:6)

要禁止显示警告,请使用脚本顶部的以下代码:

$VERBOSE = nil