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

wfauudbj  于 2022-12-18  发布在  Ruby
关注(0)|答案(5)|浏览(157)

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

wsxa1bj1

wsxa1bj11#

问题的解决方案取决于问题的原因。
1 -您正在更改之前在代码中某个位置设置的常量的值,或者试图定义与现有类或模块同名的常量。解决方案:如果你事先知道常量的值会改变,就不要使用常量;不要定义与类/模块同名的常量。
2 -你正处于一种情况下,你想重新定义一个常量有很好的理由,没有得到警告,有两个选择。
首先,可以在重新定义常量之前取消定义它(这需要一个helper方法,因为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 -您需要一个外部库来定义一个名称与您正在创建的新常量或类/模块冲突的类/模块。将代码 Package 在顶级模块名称空间中以防止名称冲突。

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


4 -和上面一样,但是你绝对需要定义一个和gem/库的类同名的类。你可以把库的类名赋给一个变量,然后清除它以备以后用途:

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'
rks48beu

rks48beu2#

试试这个:

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

qncylg1j3#

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

$VERBOSE = nil
8yparm6h

8yparm6h4#

this question的公认答案是有帮助的。我查看了Rails源代码,得到了以下内容。在加载文件之前和之后,我可以插入以下行:

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

rur96b6h5#

使用user2398029's reply,我删除警告的最简单方法是添加以下行:

before { described_class.instance_eval { remove_const(:CONSTANT_NAME) } }

相关问题