Class: Rack::Signals

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/contrib/signals.rb

Overview

Installs signal handlers that are safely processed after a request

NOTE: This middleware should not be used in a threaded environment

use Rack::Signals.new do

trap 'INT', lambda {
  puts "Exiting now"
  exit
}

trap_when_ready 'USR1', lambda {
  puts "Exiting when ready"
  exit
}

end

Defined Under Namespace

Classes: BodyWithCallback

Instance Method Summary collapse

Constructor Details

#initialize(app, &block) ⇒ Signals

Returns a new instance of Signals.



29
30
31
32
33
34
# File 'lib/rack/contrib/signals.rb', line 29

def initialize(app, &block)
  @app = app
  @processing = false
  @when_ready = nil
  instance_eval(&block)
end

Instance Method Details

#call(env) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rack/contrib/signals.rb', line 36

def call(env)
  begin
    @processing, @when_ready = true, nil
    status, headers, body = @app.call(env)

    if handler = @when_ready
      body = BodyWithCallback.new(body, handler)
      @when_ready = nil
    end
  ensure
    @processing = false
  end

  [status, headers, body]
end

#trap_when_ready(signal, handler) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'lib/rack/contrib/signals.rb', line 52

def trap_when_ready(signal, handler)
  when_ready_handler = lambda { |signal|
    if @processing
      @when_ready = lambda { handler.call(signal) }
    else
      handler.call(signal)
    end
  }
  trap(signal, when_ready_handler)
end