Skip to content

Commit

Permalink
Added Kernel#silence_stderr to silence stderr for the duration of the…
Browse files Browse the repository at this point in the history
… given block. Changed Kernel#` to print a message to stderr (like Unix) instead of raising Errno::ENOENT on Win32.

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@2899 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information
sstephenson committed Nov 7, 2005
1 parent 49c801b commit 645de33
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
4 changes: 4 additions & 0 deletions activesupport/CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
*SVN*

* Added Kernel#silence_stderr to silence stderr for the duration of the given block [Sam Stephenson]

* Changed Kernel#` to print a message to stderr (like Unix) instead of raising Errno::ENOENT on Win32 [Sam Stephenson]

* Changed 0.blank? to false rather than true since it violates everyone's expectation of blankness. #2518, #2705 [rails@jeffcole.net]

* When loading classes using const_missing, raise a NameError if and only if the file we tried to load was not present. [Nicholas Seckar]
Expand Down
26 changes: 26 additions & 0 deletions activesupport/lib/active_support/core_ext/kernel.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,32 @@ def silence_warnings
$VERBOSE = old_verbose
end

# Silences stderr for the duration of the block.
#
# silence_stderr do
# $stderr.puts 'This will never be seen'
# end
#
# $stderr.puts 'But this will'
def silence_stderr
old_stderr = STDERR.dup
STDERR.reopen(RUBY_PLATFORM =~ /mswin/ ? 'NUL:' : '/dev/null')
STDERR.sync = true
yield
ensure
STDERR.reopen(old_stderr)
end

# Makes backticks behave (somewhat more) similarly on all platforms.
# On win32 `nonexistent_command` raises Errno::ENOENT; on Unix, the
# spawned shell prints a message to stderr and sets $?. We emulate
# Unix on the former but not the latter.
def `(command) #:nodoc:
super
rescue Errno::ENOENT => e
STDERR.puts "#$0: #{e}"
end

# Method that requires a library, ensuring that rubygems is loaded
def require_library_or_gem(library_name)
begin
Expand Down
10 changes: 10 additions & 0 deletions activesupport/test/core_ext/kernel_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,14 @@ def test_silence_warnings_verbose_invariant
def test_silence_warnings_with_return_value
assert_equal 1, silence_warnings { 1 }
end

def test_silence_stderr
old_stderr_position = STDERR.tell
silence_stderr { STDERR.puts 'hello world' }
assert_equal old_stderr_position, STDERR.tell
end

def test_silence_stderr_with_return_value
assert_equal 1, silence_stderr { 1 }
end
end

0 comments on commit 645de33

Please sign in to comment.