Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger action in Rails controller on model callback

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?

like image 653
Cimm Avatar asked Nov 11 '22 05:11

Cimm


1 Answers

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

like image 84
udit mittal Avatar answered Nov 29 '22 12:11

udit mittal