On Jul 30, 2007, at 6:11 AM, ry dahl wrote:
> hello list!
>
> I like merb a lot, it frees me from dropping to mongrel every time i
> want to stream something.
>
> i have an action which will stream a list of JSON objects (separated
> by semicolons). unfortunately because of Mongrel''s write-only
header
> hash, once a Content-Length header has been written, I can never again
> tell it to not send such a thing - and streaming doesn''t work if
there
> is a Content-Length header present.
>
> I''ve been forced into returning a Proc like this from my action
>
> Proc.new do
> response.write("HTTP/1.1 200 OK\n")
> response.write("Cache-Control: no-cache\n")
> response.write("Pragma: no-cache\n")
> response.write("Content-type: text/json\n\n")
>
> while true
> sleep wait
> response.write json
> end
> response.done = true
> end
>
> writing the headers myself. i''d much prefer to do something like
this:
>
> Proc.new do
> response.send_status_no_connection_close(nil) # nil = no
> content-length
> response.send_header
> response.write("\n\n")
>
> while true
> sleep wait
> response.write json
> end
> response.done = true
> end
>
> Does anyone have suggestions on how to clean up my code so that I
> don''t need to touch raw HTTP?
>
> Thanks! ry
Hey Ry-
You could wrap up that logic in a helper method like this:
class Merb::Controller
def render_stream(&block)
Proc.new do
response.write("HTTP/1.1 200 OK\n")
response.write("Cache-Control: no-cache\n")
response.write("Pragma: no-cache\n")
response.write("Content-type: text/json\n\n")
block.call
response.done = true
end
end
end
then use it in an action:
def someaction
render_stream do
streaming = true
while streaming
sleep wait
response.write json
streaming = false if some_condition
end
end
end
Untested here so let me know how it works for you.
Cheers-
-- Ezra Zygmuntowicz
-- Founder & Ruby Hacker
-- ez at engineyard.com
-- Engine Yard, Serious Rails Hosting
-- (866) 518-YARD (9273)