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 => Proc.new { |response, output|
...
output.write("some generated text...")
...
}, :layout => false
end
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
end
In any case, the code does do what I want - perhaps someone else will find it useful.
NOTE
Comments are broken, as the typo journal system seems to have been somewhat abbandoned... argh!
Trackbacks
Use the following link to trackback from your own site:
http://journal.dedasys.com/trackbacks?article_id=167