Class: AmmuSocketManager::Middleware::SocketMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/ammu_socket_manager/middlewares/socket_middleware.rb

Constant Summary collapse

KEEPALIVE_TIME =
15

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ SocketMiddleware



11
12
13
14
# File 'lib/ammu_socket_manager/middlewares/socket_middleware.rb', line 11

def initialize(app)
 	@app     = app
 	@handler = Rails.application.config.ammu_request_handler.constantize.new
end

Instance Attribute Details

#handlerObject (readonly)

Returns the value of attribute handler.



9
10
11
# File 'lib/ammu_socket_manager/middlewares/socket_middleware.rb', line 9

def handler
  @handler
end

Instance Method Details

#call(env) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/ammu_socket_manager/middlewares/socket_middleware.rb', line 16

def call(env)
   	# Check if the Request is a Socket request and create new Connection
   	if Faye::WebSocket.websocket?(env)
     		ws = Faye::WebSocket.new(env, nil, {ping: KEEPALIVE_TIME })
     
      	ws.on :open do |event|			        
        	# Add new connection to list of all clients
        	self.handler.add_client(env, event.current_target)
      	end

	    ws.on :message do |event|
	        self.handler.run(env, event.current_target, JSON.parse(event.data))
	    end
        
      	ws.on :close do |event|
      		self.handler.remove_client(env, event.current_target)
      	end

     		ws.rack_response
    else
    	# Pass the request to the Rails App
      	@app.call(env)
    end
end