Class: Startback::Websocket::App

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

Overview

Can be used to easily implement a custom websocket protocol inside a Startback application.

Please note that this rack app is not 100% Rack compliant, since it raises any error that the block itself raises. This class aims at being backed up by a Shield and/or CatchAll middleware.

Direct Known Subclasses

Hub::App

Constant Summary collapse

JS_CLIENT =
Path.dir/'../../../dist/client.js'

Instance Method Summary collapse

Constructor Details

#initialize(context) ⇒ App

Returns a new instance of App.



16
17
18
19
20
# File 'lib/startback/websocket/app.rb', line 16

def initialize(context)
  @context = context
  @context.websocket_app = self
  @connections = []
end

Instance Method Details

#broadcast(data) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/startback/websocket/app.rb', line 34

def broadcast(data)
  data = data.to_json unless data.is_a?(String)

  @connections.each do |socket|
    socket.send(data)
  end
end

#call(env) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/startback/websocket/app.rb', line 22

def call(env)
  request = Rack::Request.new(env)
  if Faye::WebSocket.websocket?(env)
    ws = factor_and_keep(env)
    ws.rack_response
  elsif request.path_info === '/client.js'
    [200, { 'Content-Type' => 'application/javascript' }, JS_CLIENT.readlines]
  else
    [400, { 'Content-Type' => 'text/plain' }, ['Websocket only!']]
  end
end

#on_close(event, ws, env) ⇒ Object



45
46
# File 'lib/startback/websocket/app.rb', line 45

def on_close(event, ws, env)
end

#on_error(event, ws, env) ⇒ Object



48
49
# File 'lib/startback/websocket/app.rb', line 48

def on_error(event, ws, env)
end

#on_message(event, ws, env) ⇒ Object



51
52
# File 'lib/startback/websocket/app.rb', line 51

def on_message(event, ws, env)
end

#on_open(event, ws, env) ⇒ Object



42
43
# File 'lib/startback/websocket/app.rb', line 42

def on_open(event, ws, env)
end