Suppress warnings from Ruby

Journal entry
April 2, 2010

We Ruby programmers routinely do things that other programmers frown upon, and - in many cases - won’t even be allowed to do by their interpreter/compiler.

Case in point for this article, is redefining constants. In Ruby a constant isn’t constant. Creating a constant is merely a way for the programmer to indicate a value that really isn’t supposed to be changed - but if you do anyways, you’re on your own.

To that effect, Ruby by default outputs a warning if you try to redefine a constant:

warning: already initialized constant FLAGS

Occasionally you are perfectly aware of what you’re doing and redefining a constant in ie third party code might be the best way to achieve the results you need. When that’s the case, looking at that warning gets tiresome pretty quickly.

You could run your ruby scripts with -W0 to not see any warnings at all, but that’s a bit too ostrich-like a behavior. What you want is to on a case by case basis silence specific warnings.

To do this, use the following code:

module Kernel
  def suppress_warnings
    original_verbosity = $VERBOSE
    $VERBOSE = nil
    result = yield
    $VERBOSE = original_verbosity
    return result
  end
end

This allows you to do:

>> X = :foo
=> :foo
>> X = :bar
(irb):11: warning: already initialized constant X
=> :bar
>> suppress_warnings { X = :baz }
=> :baz

Remember to use this responsibly - warnings are there for a reason. Although, for extra credit, try running your Rails project with full verbosity - ie `ruby -W2 script/server` - I sure was surprised by the output.

Categories
Selling out
Did you know?
Jakob is an independent web application developer who builds awesome stuff for the web. You can hire him to build awesome stuff for you.

Comments and Trackbacks

Mihai May 5, 2010

There's also a method in Rails for this:

http://api.rubyonrails.org/classes/Kernel.html#M002564

Jakob S May 5, 2010

Oh, I didn't know that - thanks for the tip :)

Commenting on this entry has been closed.