class AmmuSocketManager::Middleware::SocketMiddleware

Constants

KEEPALIVE_TIME

Attributes

handler[R]

Public Class Methods

new(app) click to toggle source
# 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

Public Instance Methods

call(env) click to toggle source
# 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