Skip to content

Instantly share code, notes, and snippets.

@salmanasiddiqui
Last active March 20, 2024 18:58
Show Gist options
  • Save salmanasiddiqui/cd8a452d6a81bc4b050b to your computer and use it in GitHub Desktop.
Save salmanasiddiqui/cd8a452d6a81bc4b050b to your computer and use it in GitHub Desktop.
Right way to use Rails SSE for live notification
class NotificationsController < ApplicationController
def notify_me
# Rails reserve a db connection from connection pool for each request, lets put it back into connection pool.
ActiveRecord::Base.clear_active_connections!
# required header
response.headers['Content-Type'] = 'text/event-stream'
sse = ActionController::Live::SSE.new(response.stream)
@notification = nil
# This @time will be used to send a heartbeat to client, so that if client has closed his window then we will know.
@time = Time.now
begin
loop do
@notification = # put your data to be streamed here
# send heartbeat every 1 minute
if @notification || @time + 1.minute < Time.now
sse.write(@notification.to_json)
@notification = nil
@time = Time.now
end
sleep 0.001
end
rescue ActionController::Live::ClientDisconnected
# client disconnected
ensure
sse.close
end
render nothing: true
end
# Code that allows us to only mix in the live methods if we're accessing the desired action
def dispatch(name, *args)
extend ActionController::Live if name.to_s == 'notify_me'
super
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment