Class: React::Rails::HotLoader::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/hot_loader/server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host: "0.0.0.0", port: 8082, change_set_class: React::Rails::HotLoader::AssetChangeSet) ⇒ Server

Returns a new instance of Server.



9
10
11
12
13
14
# File 'lib/hot_loader/server.rb', line 9

def initialize(host:  "0.0.0.0", port: 8082, change_set_class: React::Rails::HotLoader::AssetChangeSet)
  @host = host
  @port = port
  @change_set_class = change_set_class
  @thread = nil
end

Instance Attribute Details

#change_set_classObject (readonly)

Returns the value of attribute change_set_class.



7
8
9
# File 'lib/hot_loader/server.rb', line 7

def change_set_class
  @change_set_class
end

#hostObject (readonly)

Returns the value of attribute host.



7
8
9
# File 'lib/hot_loader/server.rb', line 7

def host
  @host
end

#portObject (readonly)

Returns the value of attribute port.



7
8
9
# File 'lib/hot_loader/server.rb', line 7

def port
  @port
end

Instance Method Details

#restartObject



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/hot_loader/server.rb', line 16

def restart
  if @thread.blank? || @thread.stop?
    "[HotLoader] restarting: #{@thread}, #{@thread.try(:status)}"
    @thread = Thread.new do
      begin
        serve
      rescue StandardError => err
        React::Rails::HotLoader.log("failed to serve: #{err}\n#{err.backtrace.join("\n")}")
      end
    end
  end
end

#serveObject



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
# File 'lib/hot_loader/server.rb', line 29

def serve
  EM.run {
    React::Rails::HotLoader.log("starting WS server...")

    EM::WebSocket.run(host: host, port: port) do |ws|
      ws.onopen { React::Rails::HotLoader.log("opened a connection") }

      ws.onmessage { |msg|
        begin
          since_time =  Time.at(msg.to_i)
          changes = change_set_class.new(since: since_time)
          if changes.any?
            React::Rails::HotLoader.log("received message: #{msg}")
            React::Rails::HotLoader.log("sent response: #{changes.to_json}")
            ws.send(changes.to_json)
          end
        rescue StandardError => err
          React::Rails::HotLoader.log("message error: #{err}\n #{err.backtrace.join("\n")}")
        end
      }

      ws.onclose { React::Rails::HotLoader.log("closed a connection") }
    end

    React::Rails::HotLoader.log("started WS server")
  }
end