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
# File 'lib/thin/async.rb', line 50

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

  if block_given?
    yield self
  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

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

#doneObject

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



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

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)


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

def done?
  @done
end

#finishObject

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



90
91
92
# File 'lib/thin/async.rb', line 90

def finish
  Marker
end

#send_headersObject



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

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

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



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

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