lib/capybara/poltergeist/server_manager.rb in poltergeist-0.1.0 vs lib/capybara/poltergeist/server_manager.rb in poltergeist-0.2.0

- old
+ new

@@ -9,18 +9,16 @@ # The reason we are using EM, is because it has a WebSocket library. If there's a decent # WebSocket library that doesn't require an event loop, we can use that. class ServerManager include Singleton - TIMEOUT = 30 - - class TimeoutError < StandardError - def initialize(message) - super "Server timed out waiting for response to #{@message}" - end + class << self + attr_accessor :timeout end + self.timeout = 30 + attr_reader :sockets def initialize @instruction = nil @response = nil @@ -43,22 +41,28 @@ end def send(port, message) @message = nil - Timeout.timeout(TIMEOUT, TimeoutError.new(message)) do + Timeout.timeout(self.class.timeout) do # Ensure there is a socket before trying to send a message on it. Thread.pass until sockets[port] # Send the message thread_execute { sockets[port].send(message) } # Wait for the response message - Thread.pass until @message + Thread.pass until @message || sockets[port].nil? end - @message + if sockets[port] + @message + else + raise DeadClient.new(message) + end + rescue Timeout::Error + raise TimeoutError.new(message) end def thread_execute(&instruction) # Ensure that the thread is waiting for an instruction before we wake it up # to receive the instruction @@ -75,22 +79,22 @@ EM.run { await_instruction } end def start_websocket_server(port) EventMachine.start_server('127.0.0.1', port, EventMachine::WebSocket::Connection, {}) do |socket| - socket.onopen do - connection_opened(port, socket) - end - - socket.onmessage do |message| - message_received(message) - end + socket.onopen { connection_opened(port, socket) } + socket.onclose { connection_closed(port) } + socket.onmessage { |message| message_received(message) } end end def connection_opened(port, socket) sockets[port] = socket await_instruction + end + + def connection_closed(port) + sockets[port] = nil end def message_received(message) @message = message await_instruction