Method: Kernel#capture_output

Defined in:
lib/quality_extensions/kernel/capture_output.rb

#capture_output(output_streams = $stdout, &block) ⇒ Object

Captures the output (stdout by default) that block tries to generate and returns it as a string.

output = capture_output($stderr) { noisy_command }

output = capture_output([$stdout, $stderr]) do
  noisy_command
end

Note: If you specify more than one output stream, the entire results of each will be concatenated in the order you listed them, not necessarily in the order that you wrote to those streams.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/quality_extensions/kernel/capture_output.rb', line 35

def capture_output(output_streams = $stdout, &block)
  output_streams = [output_streams] unless output_streams.is_a? Array
  
  saved_output_streams = Dictionary.new
  output_streams.each do |output_stream|
    case output_stream.object_id
      when $stdout.object_id
        saved_output_streams[:$stdout] = $stdout
        $stdout = StringIO.new
      when $stderr.object_id
        saved_output_streams[:$stderr] = $stderr
        $stderr = StringIO.new
    end
  end

  what_they_tried_to_output = '' 
  begin
    yield
  rescue Exception
    raise
  ensure
    saved_output_streams.each do |name, output_stream|
      case name
        when :$stdout
          what_they_tried_to_output += $stdout.string
        when :$stderr
          what_they_tried_to_output += $stderr.string
      end

      # Restore the original output_stream that we saved.
      case name
        when :$stdout
          $stdout = saved_output_streams[:$stdout]
        when :$stderr
          $stderr = saved_output_streams[:$stderr]
      end
    end
  end
  return what_they_tried_to_output
end