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 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.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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



387
388
389
390
# File 'lib/sinatra/base.rb', line 387

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



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

def self.defer(*)    yield end

.scheduleObject



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

def self.schedule(*) yield end

Instance Method Details

#<<(data) ⇒ Object



410
411
412
413
# File 'lib/sinatra/base.rb', line 410

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

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



415
416
417
418
# File 'lib/sinatra/base.rb', line 415

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

#closeObject



392
393
394
395
396
# File 'lib/sinatra/base.rb', line 392

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

#closed?Boolean



422
423
424
# File 'lib/sinatra/base.rb', line 422

def closed?
  @closed
end

#each(&front) ⇒ Object



398
399
400
401
402
403
404
405
406
407
408
# File 'lib/sinatra/base.rb', line 398

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