Streaming programmatically generated content from Rails

Today, I needed to do something that I didn’t find a handy method for in Rails. The API has both a send_data and send_file method, but they are both ‘one shot’ in that you have to send all your data at once.

def generate_file
  @headers["Content-Type"] = "text/comma-separated-values;"
  @headers["Content-Disposition"] = "filename="some.file.txt";"

  i = 0

  render :text => { |response, output|
    output.write("some generated text...")
  }, :layout => false

I more or less copied that from the send_file method, and indeed, I’ll even admit that I’m not entirely sure why it works. What I don’t get is what “connects” the output variable in the Proc to an actual file descriptor somewhere. render_text doesn’t really clear things up (well, for me, at least!).

  def render_text(text = nil, status = nil) #:nodoc:
    @performed_render = true
    @response.headers['Status'] = (status || DEFAULT_RENDER_STATUS_CODE).to_s
    @response.body = text

In any case, the code does do what I want – perhaps someone else will find it useful.


Comments are broken, as the typo journal system seems to have been somewhat abbandoned… argh!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s