Class: RustWatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/rust_watcher.rb,
lib/rust_watcher/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Constructor Details

#initialize(path, &block) ⇒ RustWatcher

Returns a new instance of RustWatcher.



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

def initialize(path, &block)
  @path = path
  @block = block
  raise 'Block must take exactly two arguments' unless @block.arity == 2
end

Instance Method Details

#pathObject



11
12
13
# File 'lib/rust_watcher.rb', line 11

def path
  @path
end

#start_watcherObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rust_watcher.rb', line 15

def start_watcher
  return if watcher_running?

  child_read, parent_write = IO.pipe
  parent_read, child_write = IO.pipe

  @watcher_pid = fork do
    begin
      parent_read.close
      parent_write.close

      watch_binding(child_read, child_write)
    ensure
      child_read.close
      child_write.close
    end
  end

  child_read.close
  child_write.close

  @runner_pid = fork do
    begin
      loop do
        break unless watcher_running?
        read_pipe = IO.select([parent_read]).first.first

        if read_pipe
          output = string_presence(read_pipe.gets)
          if output
            op, file = output.split('~~~', 2)
            @block.call(op, file[1..-2])
          end
        end
      end
    ensure
      parent_read.close
    end
  end

  parent_read.close
  @writer = parent_write

  nil
end

#stop_watcherObject



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/rust_watcher.rb', line 61

def stop_watcher
  if watcher_running?
    unless @writer.closed?
      @writer.write "."
      @writer.close
    end
    Process.kill("TERM", @watcher_pid)
  end

  if runner_running?
    Process.kill("TERM", @runner_pid)
  end

  nil
end