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

3 comments:

  1. Anonymous11:08 PM

    Hide the warnings? Ugh. Bad programmer. No treat.

    ReplyDelete
  2. Anonymous9:01 AM

    Yeah, right, what if you're using someone else's code, say in a library, and you don't feel like getting into the game of shaving that particular yak right now? There are perfectly legitimate reasons for wanting to silence warnings.

    ReplyDelete
  3. Anonymous9:02 AM

    John Wilger is a dick

    ReplyDelete

Note: Only a member of this blog may post a comment.