Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Suppress Warnings in Ruby (See related posts)

#!/usr/bin/env ruby

# Kernel#with_warnings_suppressed - Supresses warnings in a given block.
# Require this file to use it or run it directly to perform a self-test.
#
# Note: The test probably won't work on Windows (haven't tried it, but
#       IO.popen likely uses fork)
# 
# Author:: Rob Pitt
# Copyright:: Copyright (c) 2008 Rob Pitt
# License:: Free to use and modify so long as credit to previous author(s) is left in place.
#

module Kernel
  # Suppresses warnings within a given block.
  def with_warnings_suppressed
    saved_verbosity = $-v
    $-v = nil
    yield
  ensure
    $-v = saved_verbosity
  end
end

#--
# Kernel#with_warnings_suppressed self-test.
if $0 == __FILE__
  # Go here for reference on rspec: http://rspec.info/examples.html
  require 'rubygems'
  require 'spec'
  
  def warning_generator
    IO.popen( '-' ) do |io|
      if io # parent          
        return io.read
      else #child
        $stderr.reopen( $stdout )
        Object.const_set( 'MONKEY', 1 )
        Object.const_set( 'MONKEY', 2 )
      end
    end
  end
  
  describe Kernel do

    it "should supress warnings" do
      with_warnings_suppressed do 
        warning_generator
      end.should == ""
    end
    
    it "should restore the previous verbosity state when it's finished" do
      with_warnings_suppressed do 
        warning_generator
      end.should == ""
      warning_generator.should match( /warning: already initialized constant MONKEY/ )
    end
    
  end
    
end
#++

You need to create an account or log in to post comments to this site.