Class: Enscalator::Helpers::SubProcess

Inherits:
Object
  • Object
show all
Defined in:
lib/enscalator/helpers/sub_process.rb

Overview

Executed command as sub-processes with stdout and stderr streams

taken from: https://nickcharlton.net/posts/ruby-subprocesses-with-stdout-stderr-streams.html

Instance Method Summary collapse

Constructor Details

#initialize(cmd) ⇒ SubProcess

Create new subprocess and execute command there

Parameters:

  • cmd (String)

    command to be executed



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/enscalator/helpers/sub_process.rb', line 11

def initialize(cmd)
  # standard input is not used
  Open3.popen3(cmd) do |_stdin, stdout, stderr, thread|
    { out: stdout, err: stderr }.each do |key, stream|
      Thread.new do
        until (line = stream.gets).nil?
          # yield the block depending on the stream
          if key == :out
            yield line, nil, thread if block_given?
          else
            yield nil, line, thread if block_given?
          end
        end
      end
    end
    thread.join # wait for external process to finish
  end
end