I am trying to wrap my head around Live Streaming with Server-Sent Events in Rails. I have a Rake task listening for file changes which adds records to the database. Once added I would like to send a SSE to the frontend.
But, the model can't send events to the frontend, the controller is responsible for that. How do I tell my controller a new record was added to the database?
My (broken) solution so far: use an EventBus with an after_save
callback in the model that announces the changes and asks the controller to listen for these messages:
require 'reloader/sse'
class SseController < ApplicationController
include ActionController::Live
def index
response.headers['Content-Type'] = 'text/event-stream'
sse = Reloader::SSE.new(response.stream)
EventBus.subscribe(:added) do |payload|
sse.write({ /* payload */ })
end
rescue IOError
ensure
sse.close
end
end
I think my request ends before the event is received meaning it will never end up in de subscribe block. Is this the right approach, if so, what am I missing?
SOLN 1: you can use rest_client gem to send a request to your controller in your after_save callback from model.
SOLN 2: Why dont you call a model method in your controller which creates the database records and then handles further action based on whether record was created or not
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With