Class: Thin::AsyncResponse

Inherits:
Object
  • Object
show all
Includes:
Rack::Response::Helpers
Defined in:
lib/thin/async.rb

Overview

Response whos body is sent asynchronously.

Constant Summary collapse

Marker =
[-1, {}, []].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env, status = 200, headers = {}) ⇒ AsyncResponse

Returns a new instance of AsyncResponse.



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/thin/async.rb', line 44

def initialize(env, status=200, headers={})
  @callback = env['async.callback']
  @body = DeferrableBody.new
  @status = status
  @headers = headers
  @headers_sent = false
  
  if block_given?
    yield self
    finish
  end
end

Instance Attribute Details

#callbackObject (readonly)

Returns the value of attribute callback.



41
42
43
# File 'lib/thin/async.rb', line 41

def callback
  @callback
end

#headersObject (readonly)

Returns the value of attribute headers.



41
42
43
# File 'lib/thin/async.rb', line 41

def headers
  @headers
end

#statusObject

Returns the value of attribute status.



42
43
44
# File 'lib/thin/async.rb', line 42

def status
  @status
end

Instance Method Details

#done(response = nil) ⇒ Object

Tell Thin the response is complete and the connection can be closed.



70
71
72
73
# File 'lib/thin/async.rb', line 70

def done(response=nil)
  send_headers(response)
  EM.next_tick { @body.succeed }
end

#finishObject

Tell Thin the response is gonna be sent asynchronously. The status code of -1 is the magic trick here.



77
78
79
# File 'lib/thin/async.rb', line 77

def finish
  Marker
end

#send_headers(response = nil) ⇒ Object



57
58
59
60
61
# File 'lib/thin/async.rb', line 57

def send_headers(response=nil)
  return if @headers_sent
  @callback.call response || [@status, @headers, @body]
  @headers_sent = true
end

#write(body) ⇒ Object Also known as: <<



63
64
65
66
# File 'lib/thin/async.rb', line 63

def write(body)
  send_headers
  @body.call(body.respond_to?(:each) ? body : [body])
end