Module: Wrong::Capturing

Included in:
Chunk, Helpers
Defined in:
lib/wrong/capturing.rb

Instance Method Summary collapse

Instance Method Details

#capturing(*streams) ⇒ Object

Usage: capturing { puts “hi” } => “hin” capturing(:stderr) { $stderr.puts “hi” } => “hin” out, err = capturing(:stdout, :stderr) { … }

see www.justskins.com/forums/closing-stderr-105096.html for more explanation



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/wrong/capturing.rb', line 10

def capturing(*streams)
  streams = [:stdout] if streams.empty?
  original = {}
  captured = {}

  # reassign the $ variable (which is used by well-behaved code e.g. puts)
  streams.each do |stream|
    original[stream] = (stream == :stdout ? $stdout : $stderr)
    captured[stream] = StringIO.new
    reassign_stream(stream, captured)
  end

  yield

  # return either one string, or an array of two strings
  if streams.size == 1
    captured[streams.first].string
  else
    [captured[streams[0]].string, captured[streams[1]].string]
  end

ensure

  streams.each do |stream|
    # bail if stream was reassigned inside the block
    if (stream == :stdout ? $stdout : $stderr) != captured[stream]
      raise "#{stream} was reassigned while being captured"
    end
    # support nested calls to capturing
    original[stream] << captured[stream].string if original[stream].is_a? StringIO
    reassign_stream(stream, original)
  end
end