如何在红宝石中发出一次警告?

时间:2010-03-04 00:57:28

标签: 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之外(即使方法不是,也会显示警告系统)叫)。

3 个答案:

答案 0 :(得分:5)

基于Chaos的回答..

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

答案 1 :(得分:2)

warnings gem隐藏了重复警告:

require 'warnings'

def danger!
  warn "Fire in the disco!"
end

danger!
danger!

Warnings.grep(/fire/)
# => [...]

Warnings.from('foo/bar.rb')
# => [...]

Warnings.from_method('danger!')
# => [...]

exit
#
# Warnings:
#
#   fire in the disco!
#      lib/foo/bar.rb:42

答案 2 :(得分:0)

你不能做这样的事吗? 我相信2个&符号会使变量变为静态。

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