Class: Roda::RodaPlugins::Streaming::Stream
- Inherits:
-
Object
- Object
- Roda::RodaPlugins::Streaming::Stream
- Includes:
- Enumerable
- Defined in:
- lib/roda/plugins/streaming.rb
Overview
Class of the response body in case you use #stream.
Three things really matter: The front and back block (back being the block generating content, front the one sending it to the client) and the scheduler, integrating with whatever concurrency feature the Rack handler is using.
Scheduler has to respond to defer and schedule.
Defined Under Namespace
Classes: Scheduler
Instance Method Summary collapse
-
#<<(data) ⇒ Object
Alias for
write. -
#callback(&block) ⇒ Object
(also: #errback)
Add the given block as a callback to call when the block closes.
-
#close ⇒ Object
If not already closed, close the connection, and call any callbacks.
-
#closed? ⇒ Boolean
Whether the connection has already been closed.
-
#each(&front) ⇒ Object
Yield values to the block as they are passed in via #<<.
-
#initialize(opts = OPTS, &back) ⇒ Stream
constructor
Handle streaming options, see Streaming for details.
-
#write(data) ⇒ Object
Add output to the streaming response body.
Constructor Details
#initialize(opts = OPTS, &back) ⇒ Stream
Handle streaming options, see Streaming for details.
92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/roda/plugins/streaming.rb', line 92 def initialize(opts=OPTS, &back) @scheduler = opts[:scheduler] || Scheduler.new(self) @back = back.to_proc @keep_open = opts[:keep_open] @callbacks = [] @closed = false if opts[:callback] callback(&opts[:callback]) end end |
Instance Method Details
#<<(data) ⇒ Object
Alias for write.
111 112 113 |
# File 'lib/roda/plugins/streaming.rb', line 111 def <<(data) write(data) end |
#callback(&block) ⇒ Object Also known as: errback
Add the given block as a callback to call when the block closes.
116 117 118 119 |
# File 'lib/roda/plugins/streaming.rb', line 116 def callback(&block) return yield if closed? @callbacks << block end |
#close ⇒ Object
If not already closed, close the connection, and call any callbacks.
126 127 128 129 130 |
# File 'lib/roda/plugins/streaming.rb', line 126 def close return if closed? @closed = true @scheduler.schedule{@callbacks.each(&:call)} end |
#closed? ⇒ Boolean
Whether the connection has already been closed.
133 134 135 |
# File 'lib/roda/plugins/streaming.rb', line 133 def closed? @closed end |
#each(&front) ⇒ Object
Yield values to the block as they are passed in via #<<.
138 139 140 141 142 143 144 145 146 147 148 |
# File 'lib/roda/plugins/streaming.rb', line 138 def each(&front) @front = front @scheduler.defer do begin @back.call(self) rescue Exception => e @scheduler.schedule{raise e} end close unless @keep_open end end |
#write(data) ⇒ Object
Add output to the streaming response body.
105 106 107 108 |
# File 'lib/roda/plugins/streaming.rb', line 105 def write(data) @scheduler.schedule{@front.call(data.to_s)} self end |