/
rails.rb
90 lines (76 loc) · 1.8 KB
/
rails.rb
1
2
3
4
5
6
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
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
require 'pty'
require 'waiting_on_rails/player'
module WaitingOnRails
class Exit < Exception; end
class Rails
def initialize(music_player, ding_player = nil)
@music_player = music_player
@ding_player = ding_player
end
def run(args)
if not should_play_music?(args)
exec_rails_command(args)
end
spawn_rails_subprocess(args) do |output, pid|
@music_player.start(loop: true)
handle_signals(pid, output)
main_loop(output)
end
rescue Exit
exit(1)
ensure
@music_player.stop
end
private
def spawn_rails_subprocess(args)
PTY.spawn('rails', *args) do |output, input, pid|
yield output, pid
end
end
def exec_rails_command(args)
exec 'rails', *args
end
def main_loop(io)
loop do
begin
line = io.readline
puts line
if matches_server_start?(line)
@music_player.stop
sleep 0.5
@ding_player.start if @ding_player
end
rescue EOFError
break
rescue Errno::EIO
raise Exit
end
end
end
def handle_signals(pid, output)
%w(TERM INT).each do |signal|
Signal.trap(signal) do
Process.kill(signal, pid)
loop do
begin
puts output.readline
rescue EOFError
break
end
end
raise Exit
end
end
end
def should_play_music?(args)
args.find { |arg| ['server', 's'].include? arg }
end
def matches_server_start?(string)
patterns = [
'WEBrick::HTTPServer#start', # WEBrick
'Listening on', # Thin, Puma
]
patterns.any? { |p| string.include?(p) }
end
end
end