Skip to content

Instantly share code, notes, and snippets.

@julik
Created February 24, 2024 01:47
Show Gist options
  • Save julik/1f41da27ad82d2a21ea8ba0ce6a89c08 to your computer and use it in GitHub Desktop.
Save julik/1f41da27ad82d2a21ea8ba0ce6a89c08 to your computer and use it in GitHub Desktop.
class StreamingController < ApplicationController
class Writer
def initialize(&blk)
@blk = blk
end
def write(stuff)
@blk.call(stuff)
stuff.bytesize
end
end
class EnumerableBody
def initialize(&streaming_block_accepting_io)
@streaming_block_accepting_io = streaming_block_accepting_io
end
def each(&blk)
writer = Writer.new(&blk)
@streaming_block_accepting_io.yield(writer)
end
end
def index
stream do |io|
100.times {
io.write "hello world\n"
}
end
end
def stream(&streaming_block_accepting_io)
headers.delete("Content-Length")
headers["Transfer-Encoding"] = "chunked"
self.response_body = Rack::Chunked::Body.new(EnumerableBody.new(&streaming_block_accepting_io))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment