Class: Websocket

Inherits:
Object
  • Object
show all
Defined in:
lib/server_skeleton/lib/websocket.rb

Instance Method Summary collapse

Constructor Details

#initialize(req) ⇒ Websocket

A wrapper over an underlying websocket API If ever the websocket server dependency would need to change, this file would be a place to swap out libraries.

With each handler (open, close, message) is passed the request object in addition to the websocket connection object and any additional arguments (such as message)

If this is being initialized, the request is assumed to be of the websocket variety.

Operations in this class are implemented in a stack which needs to be finalized by #ready.

for example:

socket = Websocket.new(request)
socket.onopen { |req, socket| }
socket.onclose { |req, socket| }
socket.onmessage { |req, socket, msg| }
socket.ready


24
25
26
27
28
# File 'lib/server_skeleton/lib/websocket.rb', line 24

def initialize(req)
  @req = req
  @socket = Faye::WebSocket.new(req.env)
  @stack = {}
end

Instance Method Details

#onclose(&blk) ⇒ Object



34
35
36
# File 'lib/server_skeleton/lib/websocket.rb', line 34

def onclose &blk
  @stack[:onclose] = blk
end

#onmessage(&blk) ⇒ Object



38
39
40
# File 'lib/server_skeleton/lib/websocket.rb', line 38

def onmessage &blk
  @stack[:onmessage] = blk
end

#onopen(&blk) ⇒ Object



30
31
32
# File 'lib/server_skeleton/lib/websocket.rb', line 30

def onopen &blk
  @stack[:onopen] = blk
end

#readyObject



42
43
44
45
46
47
# File 'lib/server_skeleton/lib/websocket.rb', line 42

def ready
  @socket.on(:open) { @stack[:onopen].call @req, @socket }
  @socket.on(:close) { @stack[:onclose].call @req, @socket }
  @socket.on(:message) { |msg| @stack[:onmessage].call @req, @socket, msg }
  @socket.rack_response
end