Friday, May 19, 2006

Hiding the Parenthesize Warning in Ruby

If you execute the sample code for the Executing an internal DSL in multiple contexts entry you will see results similar to this:
Context One:
(eval):1: warning: parenthesize argument(s) for future version
(eval):1: warning: parenthesize argument(s) for future version
(eval):1: warning: parenthesize argument(s) for future version
(eval):1: warning: parenthesize argument(s) for future version
(eval):1: warning: parenthesize argument(s) for future version
(eval):1: warning: parenthesize argument(s) for future version
(eval):1: warning: parenthesize argument(s) for future version
(eval):1: warning: parenthesize argument(s) for future version
$5-$10 Limit
action open
position floor
...
The code was just sample code so I wasn't very concerned with hiding the warnings; however, since several people asked how to do it I thought I'd do a quick follow up entry.

The code required to silence warnings can be found in the Rails framework (activesupport/lib/active_support/core_ext/kernel/reporting).
module Kernel
def silence_warnings
old_verbose, $VERBOSE = $VERBOSE, nil
yield
ensure
$VERBOSE = old_verbose
end
end
After adding the above code to your codebase (or, if you are writing a Rails app it's already included) you can execute your code as a block to silence_warnings and no warnings will be shown.
silence_warnings do
puts "\nContext One:"
ContextOne.execute(script) do |notification|
Broadcast.notify(*notification)
end

puts "\nContext Two:"
ContextTwo.execute(script) do |stakes|
puts ContextTwo.sym_to_stakes(stakes)
end

puts "\nContext Three"
ContextThree.execute(script) do |positions|
puts positions
end
end

The results are much quieter after silencing the warnings
Context One:
$5-$10 Limit
action open
position floor
$1-$2 No Limit
action open
position floor
$5-$10 Limit
action announce
position brush
$1-$2 No Limit
action announce
position brush

Context Two:
$5-$10 Limit
$1-$2 No Limit
$5-$10 Limit
$1-$2 No Limit

Context Three
floor
floor
brush
brush
Updated Sample Code
Post a Comment