开发者

How do I make a warning only occur once in ruby?

开发者 https://www.devze.com 2022-12-21 17:41 出处:网络
Is it possible to tell ruby to give a warning only once, rather than multiple times? class SoylentGreen

Is it possible to tell ruby to give a warning only once, rather than multiple times?

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

produces

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!

whereas ideally I'd like it to occur only once.

I'm not using rails, and have access to ruby 1.8 and 1.9.

Alternatives would include writing my own warning system (which'd cover only deliberate warnings like开发者_如何学Go this), or putting the warning outside of SoylentGreen#eat (which'd cause it to be displayed even if the method wasn't called).


Based on Chaos's answer..

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


The warnings gem hides duplicate warnings:

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


Couldn't you do something like this? I believe the 2 ampersands make a variable static.

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

精彩评论

暂无评论...
验证码 换一张
取 消