Class: Hyde::Decap::Subprocess

Inherits:
Object
  • Object
show all
Defined in:
lib/hyde/decap/subprocess.rb

Instance Method Summary collapse

Constructor Details

#initialize(cmd, &block) ⇒ Subprocess

Returns a new instance of Subprocess.



7
8
9
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
# File 'lib/hyde/decap/subprocess.rb', line 7

def initialize(cmd, &block)
  Open3.popen3(cmd) do |stdin, stdout, stderr, thread|
    trap("INT") {
      Jekyll.logger.info "Decap:", "shutting down server and Decap CMS Proxy"
      thread.exit
    }

    # read each stream from a new 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
          elsif block
            yield nil, line, thread
          end
        end
      rescue IOError => e
        if e.message != "stream closed in another thread"
          raise e
        end
      end
    end

    thread.join # don't exit until the external process is done
  end
end