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
- Please Comment on GitHub
- Next Article: Ruby has Character
- Previous Article: What the Regex?