class Exec

Attributes

color[RW]
debug[RW]

Public Class Methods

new(cmd, **options) click to toggle source
# File lib/exec.rb, line 8
def initialize(cmd, **options)
    handle_exception
    @i, @o, s = Open3.popen2(cmd)
    # Debug msg
    @debug = (options.has_key? :debug) ? options[:debug] : true
    # Log color
    Rainbow.enabled = false if options[:color] == false
end

Public Instance Methods

gets() click to toggle source
# File lib/exec.rb, line 35
def gets
    read_until "\n"
end
interactive() click to toggle source
# File lib/exec.rb, line 50
def interactive
    loop do
        r = IO.select [@o, $stdin]
        if r[0].include? @o
            read 1
        elsif r[0].include? $stdin
            @i.write $stdin.read(1)
        end
    end
end
puts(data) click to toggle source
# File lib/exec.rb, line 31
def puts(data)
    write "#{data}\n"
end
read(size) click to toggle source
# File lib/exec.rb, line 17
def read(size)
    @o.read(size).tap {|data| write_flush $stdout, data.color(:cyan) if @debug}
end
read_until(str) click to toggle source
# File lib/exec.rb, line 39
def read_until(str)
    result = ""
    loop do
        result << @o.read(1)
        if result.end_with? str
            write_flush $stdout, result.color(:cyan) if @debug
            return result
        end
    end
end
readpartial(size) click to toggle source
# File lib/exec.rb, line 21
def readpartial(size)
    @o.readpartial(size).tap {|data| write_flush $stdout, data.color(:cyan) if @debug}
end
write(data) click to toggle source
# File lib/exec.rb, line 25
def write(data)
    data = data.to_s if data.is_a? Integer
    write_flush $stdout, data.color(:yellow) if @debug
    write_flush @i, data
end

Private Instance Methods

handle_exception() click to toggle source
# File lib/exec.rb, line 67
def handle_exception
    trap "SIGINT" do
        $stdout.puts
        $stdout.puts "interrupted"
        exit -1
    end
end
write_flush(fd, data) click to toggle source
# File lib/exec.rb, line 62
def write_flush(fd, data)
    fd.write data
    fd.flush
end