Class: Sinatra::Helpers::Stream

Inherits:
Object
  • Object
show all
Defined in:
lib/sinatra/base.rb

Overview

Class of the response body in case you use #stream.

Three things really matter: The front and back block (back being the blog 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.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scheduler = self.class, keep_open = false, &back) ⇒ Stream

Returns a new instance of Stream.



266
267
268
269
# File 'lib/sinatra/base.rb', line 266

def initialize(scheduler = self.class, keep_open = false, &back)
  @back, @scheduler, @keep_open = back.to_proc, scheduler, keep_open
  @callbacks, @closed = [], false
end

Class Method Details

.deferObject



264
# File 'lib/sinatra/base.rb', line 264

def self.defer(*)    yield end

.scheduleObject



263
# File 'lib/sinatra/base.rb', line 263

def self.schedule(*) yield end

Instance Method Details

#<<(data) ⇒ Object



289
290
291
292
# File 'lib/sinatra/base.rb', line 289

def <<(data)
  @scheduler.schedule { @front.call(data.to_s) }
  self
end

#callback(&block) ⇒ Object Also known as: errback



294
295
296
297
# File 'lib/sinatra/base.rb', line 294

def callback(&block)
  return yield if @closed
  @callbacks << block
end

#closeObject



271
272
273
274
275
# File 'lib/sinatra/base.rb', line 271

def close
  return if @closed
  @closed = true
  @scheduler.schedule { @callbacks.each { |c| c.call }}
end

#each(&front) ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
# File 'lib/sinatra/base.rb', line 277

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