Sha256: e412b5ed1fcc962d8914e5bef69b07e1e0c5a55a02fc2245a1da0dd7f557e690

Contents?: true

Size: 1.06 KB

Versions: 31

Compression:

Stored size: 1.06 KB

Contents

module CaptureIo
  def capture(output = :out, &block)
    _, out = swap_io(output, &block)
    out
  end

  def silence(&block)
    block_result = nil
    swap_io(:out) do
      block_result,_ = swap_io(:err, &block)
    end
    block_result
  end

  def swap_io(output = :out, &block)
    java_import 'java.io.PrintStream'
    java_import 'java.io.ByteArrayOutputStream'
    java_import 'java.lang.System'

    ruby_original_stream = output == :out ? $stdout.dup : $stderr.dup
    java_original_stream = System.send(output) # :out or :err
    ruby_buf = StringIO.new
    java_buf = ByteArrayOutputStream.new

    case output
    when :out
      $stdout = ruby_buf
      System.setOut(PrintStream.new(java_buf))
    when :err
      $stderr = ruby_buf
      System.setErr(PrintStream.new(java_buf))
    end

    [block.call, ruby_buf.string + java_buf.toString]
  ensure
    case output
    when :out
      $stdout = ruby_original_stream
      System.setOut(java_original_stream)
    when :err
      $stderr = ruby_original_stream
      System.setErr(java_original_stream)
    end
  end
end

Version data entries

31 entries across 31 versions & 4 rubygems

Version Path
embulk-input-zendesk-0.2.14 test/capture_io.rb
embulk-input-zendesk-0.2.13 test/capture_io.rb
embulk-input-zendesk-0.2.11 test/capture_io.rb
embulk-input-zendesk-0.2.12 test/capture_io.rb
embulk-input-zendesk-0.2.10 test/capture_io.rb
embulk-input-zendesk-0.2.9 test/capture_io.rb
embulk-input-zendesk-0.2.8 test/capture_io.rb
embulk-input-zendesk-0.2.7 test/capture_io.rb
embulk-input-zendesk-0.2.6 test/capture_io.rb
embulk-input-zendesk-0.1.13 test/capture_io.rb
embulk-parser-fixed-0.1.0 test/capture_io.rb
embulk-input-zendesk-0.1.12 test/capture_io.rb
embulk-input-zendesk-0.1.11 test/capture_io.rb
embulk-input-zendesk-0.1.10 test/capture_io.rb
embulk-parser-unpack-0.1.5 test/capture_io.rb
embulk-input-zendesk-0.1.9 test/capture_io.rb
embulk-input-zendesk-0.1.8 test/capture_io.rb
embulk-parser-query_string-0.3.2 test/capture_io.rb
embulk-input-zendesk-0.1.7 test/capture_io.rb
embulk-input-zendesk-0.1.6 test/capture_io.rb