Class: Rack::App::Streamer

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/app/streamer.rb

Overview

Copyright © 2007, 2008, 2009 Blake Mizerany Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016 Konstantin Haase

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.

Instance Method Summary collapse

Constructor Details

#initialize(env, options = {}, &back) ⇒ Streamer

Returns a new instance of Streamer.

[View source]

15
16
17
18
19
20
21
22
# File 'lib/rack/app/streamer.rb', line 15

def initialize(env, options={}, &back)
  @serializer = env[::Rack::App::Constants::ENV::SERIALIZER]
  @extname = env[::Rack::App::Constants::ENV::EXTNAME]
  @scheduler = options[:scheduler] || Rack::App::Streamer::Scheduler.by_env(env)
  @keep_open = options[:keep_open] || false
  @back = back.to_proc
  @callbacks, @closed = [], false
end

Instance Method Details

#<<(data) ⇒ Object

[View source]

42
43
44
45
# File 'lib/rack/app/streamer.rb', line 42

def <<(data)
  @scheduler.schedule { @front.call(@serializer.serialize(@extname, data)) }
  self
end

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

[View source]

47
48
49
50
# File 'lib/rack/app/streamer.rb', line 47

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

#closeObject

[View source]

24
25
26
27
28
# File 'lib/rack/app/streamer.rb', line 24

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

#closed?Boolean

Returns:

  • (Boolean)
[View source]

54
55
56
# File 'lib/rack/app/streamer.rb', line 54

def closed?
  @closed
end

#each(&front) ⇒ Object

[View source]

30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rack/app/streamer.rb', line 30

def each(&front)
  @front = front
  @scheduler.defer do
    begin
      @back.call(self)
    rescue Exception => ex
      @scheduler.schedule { raise(ex) }
    end
    close unless @keep_open
  end
end