恼人的“警告:已经初始化的常数”的解决方案。信息 [英] solutions to the annoying "warning: already initialized constant" message
问题描述
今天,我偶然发现了一个有关Ruby常量的棘手问题。在我们的团队中,有人创建了一个模块,该模块包含在多个模型中。在我们的(规范)测试输出中,这导致生成警告消息,例如:
Today I've stumbled upon a tricky issue with Ruby constants. In our team someone created a module, which is included into multiple models. In our (spec) test output this results into warning messages such as:
/home/ayrton/project/lib/life_cycle.rb: 5:警告:已经初始化的
常量RESET
/home/ayrton/project/lib/life_cycle.rb:5: warning: already initialized constant RESET
一种解决方法是,像这样声明您的常量:
One way to solve this is, is to declare your constants like this:
module LifeCycle
unless (const_defined?(:RESET))
RESET = 'reset'
end
#...
end
我还阅读了Avdi Grimm撰写的博客文章,其中提供了另一种方法解决方案,我想知道您对此事有何看法。
I've also read a blog post, written by Avdi Grimm, which provides an alternative solution, I was wondering what your opinions are, regarding this matter.
推荐答案
我今天遇到了同样的问题,找到了一个简单的解决方案。
I encountered this same problem today and found a simple solution.
由于警告是试图重新分配具有相同值的常量,因此我只是更改了
Since the warning is from trying to reassign a constant with its same value, I just changed
module LifeCycle
RESET = 'reset'
end
至
module LifeCycle
RESET ||= 'reset'
end
这很注意警告,并且比检查是否定义了每个常量要简单得多。让我知道您是否找到更好的解决方案。
This took care of the warning and is a lot simpler than checking if each constant is defined. Let me know if you find a better solution.
这篇关于恼人的“警告:已经初始化的常数”的解决方案。信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!