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.



35
36
37
38
39
40
# File 'lib/rack/contrib/signals.rb', line 35

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

Instance Method Details

#call(env) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rack/contrib/signals.rb', line 42

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



58
59
60
61
62
63
64
65
66
67
# File 'lib/rack/contrib/signals.rb', line 58

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