ruby - 如何在 ruby​​ 中只发出一次警告?

标签 ruby warnings

是否可以告诉 ruby​​ 只发出一次警告,而不是多次发出警告?

class SoylentGreen
  def eat
    warn "Algae harvesting not implemented. Soylent green is people!"
  end
end

5.times do
  soylent_green = SoylentGreen.new
  soylent_green.eat
end

产生

Algae harvesting not implemented. Soylent green is people!
Algae harvesting not implemented. Soylent green is people!
Algae harvesting not implemented. Soylent green is people!
Algae harvesting not implemented. Soylent green is people!
Algae harvesting not implemented. Soylent green is people!

而理想情况下,我希望它只发生一次。

我没有使用 Rails,但可以访问 ruby​​ 1.8 和 1.9。

备选方案包括编写我自己的警告系统(它只涵盖像这样的故意警告),或者将警告放在 SoylentGreen#eat 之外(这会导致它显示,即使该方法未被调用)。

最佳答案

基于混沌的回答..

class SoylentGreen
  def eat
    warn_once "Algae harvesting not implemented. Soylent green is people!"
  end
  def warn_once(msg)
    @@warned||=false
    if not @@warned then
       @@warned = true
       warn msg
    end
  end
end

关于ruby - 如何在 ruby​​ 中只发出一次警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2376184/

相关文章:

ruby-on-rails - 用于显示操作的 URL 中的自定义参数

ruby - 在 Ruby 模块中使用辅助方法

python - 如何使用 pytest 断言不引发警告

perl - 在开发过程中,我应该如何将 Perl 警告升级为 fatal error ?

ruby - Puppet list - 'sudo' 命令?

sql - rails/SQL : count the number of consecutive records having a specific status

ruby-on-rails - 过度提交 RailsS​​chemaUpToDate 在 --run 时通过但在提交时失败

ios - Xcode: "Scene is unreachable due to lack of entry points"但找不到

php - 使用PHP的“Notice: Undefined variable”,“Notice: Undefined index”和“Notice: Undefined offset”

gcc - 使用 GCC 的 -Wpointer-arith