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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of AsyncResponse.



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/thin/async.rb', line 50

def initialize(env, status=200, headers={})
  @callback = env['async.callback']
  @close = env['async.close']
  @body = DeferrableBody.new
  @status = status
  @headers = headers
  @headers_sent = false
  @done = false

  if block_given?
    yield self
  end
end

Instance Attribute Details

#callback(&block) ⇒ Object (readonly)

Specify a block to be executed when the response is done

Calling this method before the response has completed will cause the callback block to be stored on an internal list. If you call this method after the response is done, the block will be executed immediately.



96
97
98
# File 'lib/thin/async.rb', line 96

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

Class Method Details

.perform(*args, &block) ⇒ Object

Creates a instance and yields it to the block given returns the async marker



46
47
48
# File 'lib/thin/async.rb', line 46

def self.perform(*args, &block)
  new(*args, &block).finish
end

Instance Method Details

#cancel_callback(block) ⇒ Object

Cancels an outstanding callback to &block if any. Undoes the action of #callback.



103
104
105
# File 'lib/thin/async.rb', line 103

def cancel_callback block
  @close.cancel_callback(block)
end

#doneObject

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



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

def done
  return if done?
  send_headers
  EM.next_tick { @body.succeed }
  @done = true
end

#done?Boolean

Tells if the response has already been completed

Returns:

  • (Boolean)


85
86
87
# File 'lib/thin/async.rb', line 85

def done?
  @done
end

#finishObject

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



109
110
111
# File 'lib/thin/async.rb', line 109

def finish
  Marker
end

#send_headersObject



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

def send_headers
  return if @headers_sent
  @callback.call [@status, @headers, @body]
  @headers_sent = true
end

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



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

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