开发者

Is it possible to set the status code while using render :text => proc

开发者 https://www.devze.com 2023-02-11 16:15 出处:网络
Rails supports streaming text updates from w/in action controller: render :text => proc { |response, output|

Rails supports streaming text updates from w/in action controller:

render :text => proc { |response, output|
  10_000_000.times do |i|
   开发者_如何学Python output.write("This is line #{i}\n")
  end
}

Similarly, text can be rendered w/ an http status code:

render :text => ":(", :status => 400

I am wondering, if inside the 10 million writes we encounter an error, is it possible to close the stream w/ a status code?

Thank you for your time!


You can close a stream by catching the error and breaking out of the proc. You can then pass an error message or simply close your stream. For example:

render :text => proc { |response, output|
  10_000_000.times do |i|
    begin
      output.write("This is line #{i}\n")
      raise StandardError, "reached line 100!" if i == 100
    rescue Exception => e
      response.status = 400
      output.write(e.message)
      break
    end
  end
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号