This repository has been archived by the owner on Aug 6, 2018. It is now read-only.
/
middleware.rb
61 lines (52 loc) · 1.79 KB
/
middleware.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
require "monitor"
require "set"
require "filewatcher"
module LivereloadRails
class Middleware
ASYNC_RESPONSE = [-1, {}, []]
def initialize(app, assets:, matchers: LivereloadRails.matchers)
@app = app
@clients = Set.new
@clients.extend(MonitorMixin)
assets.configure do |environment|
@watcher = Watcher.new(LivereloadRails.paths.call(environment.paths), matchers: matchers) do |file|
client_path = "#{assets.prefix}/#{file}"
clients = @clients.synchronize { @clients.dup }
LivereloadRails.logger.debug "Reloading #{clients.size} clients with #{client_path}."
clients.each { |client| client.reload(client_path) }
end
@watcher_thread = Thread.new do
Thread.current.abort_on_exception = true
@watcher.run
end
end
end
def call(env)
if env["PATH_INFO"] == "/livereload"
websocket = LivereloadRails::WebSocket.from_rack(env) do |ws|
client = LivereloadRails::Client.new(ws)
ws.on(:open) do
@clients.synchronize { @clients.add(client) }
LivereloadRails.logger.debug "#{client} joined: #{@clients.size}."
end
ws.on(:close) do
@clients.synchronize { @clients.delete(client) }
LivereloadRails.logger.debug "#{client} left: #{@clients.size}."
end
end
if websocket
ASYNC_RESPONSE
else
@app.call(env)
end
elsif env["PATH_INFO"] == "/livereload.js"
prefix = Rails.application.config.assets.prefix
file = Rails.application.assets.find_asset("livereload.js").digest_path
url = File.join(prefix, file)
[302, { "Location" => url }, []]
else
@app.call(env)
end
end
end
end