Class: Cmds::IOHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/cmds/io_handler.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeIOHandler

Returns a new instance of IOHandler.



5
6
7
8
9
# File 'lib/cmds/io_handler.rb', line 5

def initialize
  @in = nil
  @out = $stdout
  @err = $stderr
end

Instance Attribute Details

#errObject

Returns the value of attribute err.



3
4
5
# File 'lib/cmds/io_handler.rb', line 3

def err
  @err
end

#inObject

Returns the value of attribute in.



3
4
5
# File 'lib/cmds/io_handler.rb', line 3

def in
  @in
end

#outObject

Returns the value of attribute out.



3
4
5
# File 'lib/cmds/io_handler.rb', line 3

def out
  @out
end

Instance Method Details

#on_err(&block) ⇒ Object



30
31
32
# File 'lib/cmds/io_handler.rb', line 30

def on_err &block
  @err = block
end

#on_out(&block) ⇒ Object



21
22
23
# File 'lib/cmds/io_handler.rb', line 21

def on_out &block
  @out = block
end

#startObject



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
75
# File 'lib/cmds/io_handler.rb', line 43

def start
  # Initialize a thread-safe queue for passing output from the IO threads
  # back to the main thread
  @queue = Queue.new
  
  # if out is a proc, it's not done
  out_done = ! @out.is_a?(Proc)
  # same for err
  err_done = ! @err.is_a?(Proc)

  until out_done && err_done
    key, line = @queue.pop
    
    case key
    when :out
      if line.nil?
        out_done = true
      else
        handle_line @out, line
      end

    when :err
      if line.nil?
        err_done = true
      else
        handle_line @err, line
      end

    else
      raise "bad key: #{ key.inspect }"
    end
  end
end

#thread_send_err(line) ⇒ Object

called in seperate thread handling process IO



35
36
37
# File 'lib/cmds/io_handler.rb', line 35

def thread_send_err line
  @queue << [:err, line]
end

#thread_send_line(sym, line) ⇒ Object



39
40
41
# File 'lib/cmds/io_handler.rb', line 39

def thread_send_line sym, line
  @queue << [sym, line]
end

#thread_send_out(line) ⇒ Object

called in seperate thread handling process IO



26
27
28
# File 'lib/cmds/io_handler.rb', line 26

def thread_send_out line
  @queue << [:out, line]
end