![](/style/images/good.png)
7
![](/style/images/bad.png)
Idiosyncratic Ruby: Warning: The Module
source link: https://idiosyncratic-ruby.com/65-warning-the-module.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Warning: The Module
Starting with Ruby 2.5¹ it is possible to customize the behavior of Kernel#warn through the Warning module. Here is how:
def Warning.warn(w)
# super calls the original behavior, which is printing to $stderr
super "\e[31;1mRUBY WARNING: \e[22m#{w.sub(/warning: /, '')}\e[0m"
end
# # #
# examples
warn "test"
# => RUBY WARNING: test
{ a: 1, a: 2 }
# => RUBY WARNING: (irb):4: key :a is duplicated and overwritten on line 4
$VERBOSE = true # shows level 2 warnings
def a() end
def a() end
# => RUBY WARNING: (irb):8: method redefined; discarding old a
# => RUBY WARNING: (irb):6: previous definition of a was here
You can unlock some more warning features by using Jeremy Evans' warning gem:
require "warning"
Warning.ignore /duplicated and overwritten/
{ a: 1, a: 2 }
# => nothing
$VERBOSE = true
Warning.ignore :method_redefined
def a() end
def a() end
# => nothing
¹ Although the Warning module existed in Ruby 2.4 already, Kernel#warn did not make use of it yet
Further Reading
More Idiosyncratic Ruby
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK