How to make a warning only once in a ruby?

Is it possible to tell ruby ​​to alert only once, and not several 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 would like this to happen only once.

I do not use rails and have access to ruby ​​1.8 and 1.9.

Alternatives would include recording my own warning system (which closed only deliberate warnings like this), or putting a warning outside SoylentGreen#eat(which would cause it to display even if the method was not called).

+3
source share
3 answers

Based on Chaos response.

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
+5
source

warnings gem hides repeated 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
+2

- ? , 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
0

Source: https://habr.com/ru/post/1735356/


All Articles