是否可以在使用render时设置状态代码:text => PROC

时间:2011-02-16 17:32:55

标签: ruby-on-rails

Rails支持来自w / in action controller的流式文本更新:

render :text => proc { |response, output|
  10_000_000.times do |i|
    output.write("This is line #{i}\n")
  end
}

同样,可以使用http状态代码呈现文本:

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

我想知道,如果在1000万次写入中我们遇到错误,是否可以使用状态代码关闭流?

感谢您的时间!

1 个答案:

答案 0 :(得分:1)

您可以通过捕获错误并中断proc来关闭流。然后,您可以传递错误消息或只是关闭您的流。例如:

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
}
相关问题