我需要在渲染页面后对远程服务做请求
我的 Controller :
after_filter :remote_action, only: :update
def update
@res = MyService.do_action foo, bar
return render json: @res[:json], status: @res[:status] unless @res[:success]
end
def remote_action
# There is remote http request
end
我需要在渲染页面后调用 remote_action 方法
最佳答案
after_filter
在模板转换为 html 之后运行,但 之前 html 作为响应发送给客户端。因此,如果您正在做一些缓慢的事情,例如发出远程 http 请求,那么这将减慢您的响应速度,因为它需要等待该远程请求完成:换句话说,远程请求将阻止您的响应。
为了避免阻塞,你可以 fork 出一个不同的线程:看看
https://github.com/tra/spawnling
使用它,您只需将代码更改为
def remote_action
Spawnling.new do
# There is remote http request
end
end
在响应被发回之前,远程调用仍然会被触发,但是因为它已经被 fork 到一个新的线程中,响应不会等待远程请求返回,它会立即发生。
您还可以查看 https://github.com/collectiveidea/delayed_job ,它将作业放入数据库表中,一个单独的进程将在其中提取并执行它们。
关于ruby-on-rails - 渲染后如何调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33240800/