-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
chat_controller.rb
35 lines (29 loc) · 918 Bytes
/
chat_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
require 'chat'
require 'async/websocket/adapters/rails'
class ChatController < ApplicationController
def index
end
def connect
channel = params.fetch(:channel, 'chat.general')
self.response = Async::WebSocket::Adapters::Rails.open(request) do |connection|
client = Chat::Redis.instance
subscription_task = Async do
# Subscribe to the channel and broadcast incoming messages:
client.subscribe(channel) do |context|
while true
type, name, message = context.listen
# The message is text, but contains JSON.
connection.send_text(message)
connection.flush
end
end
end
# Perpetually read incoming messages and publish them to Redis:
while message = connection.read
client.publish(channel, message.buffer)
end
ensure
subscription_task&.stop
end
end
end