Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to execute a method after sending a response back to the browser in Rails?

I'm trying to run an action after I send a response back to the client in Rails. Is it possible to do this without background workers or creating new threads?

I looked into the after_filter callback, but it seems like this only lets you execute code before you render the view / response.

Thanks

like image 831
theCuriousGee Avatar asked Dec 12 '25 19:12

theCuriousGee


1 Answers

Short answer: No, it is not possible. You have to use threads or some kind of delayed job framework (Sidekiq, Resque, etc.).

Long answer: you actually can use ActionController::Live to control the moment on which your response is 'flushed' to client.

Modified example from the docs:

class MyController < ActionController::Base
  include ActionController::Live

  def stream
    begin
      response.headers['Content-Type'] = 'text/event-stream'
      100.times {
        response.stream.write "hello world\n"
        sleep 1
      }
    ensure
      response.stream.close
    end
    do_my_after_response_job
  end
end
like image 136
EugZol Avatar answered Dec 14 '25 09:12

EugZol