Created
February 24, 2024 01:47
-
-
Save julik/1f41da27ad82d2a21ea8ba0ce6a89c08 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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