Class: Collective::SignalHook

Inherits:
Object
  • Object
show all
Defined in:
lib/collective/utilities/signal_hook.rb

Overview

Allows you to add hooks without worrying about restoring the chain when you are done.

Hooks can be nested.
Only the most deeply nested handler will be called.

Usage:
  hook = SignalHook.trap("TERM") { ... my term handler }
  hook.attempt do
    ... my long action
  end
  # at this point, term handler has been removed from chain

  or
  SignalHook.trap("QUIT") { foo.quit! }.attempt { foo.run }

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#chain=(value) ⇒ Object (writeonly)

Sets the attribute chain

Parameters:

  • value

    the value to set the attribute chain to.



21
22
23
# File 'lib/collective/utilities/signal_hook.rb', line 21

def chain=(value)
  @chain = value
end

#local=(value) ⇒ Object (writeonly)

Sets the attribute local

Parameters:

  • value

    the value to set the attribute local to.



21
22
23
# File 'lib/collective/utilities/signal_hook.rb', line 21

def local=(value)
  @local = value
end

Class Method Details

.trap(signal, &block) ⇒ Object



38
39
40
41
42
43
44
# File 'lib/collective/utilities/signal_hook.rb', line 38

def trap( signal, &block )
  hook       = new
  hook.local = block
  previous   = Signal.trap( signal ) { hook.trigger }
  hook.chain = previous if previous && previous.kind_of?(Proc)
  hook
end

Instance Method Details

#attempt(&block) ⇒ Object



31
32
33
34
35
# File 'lib/collective/utilities/signal_hook.rb', line 31

def attempt( &block )
  yield
ensure
  @local = false
end

#triggerObject



23
24
25
26
27
28
29
# File 'lib/collective/utilities/signal_hook.rb', line 23

def trigger
  if @local then
    @local.call
  elsif @chain
    @chain.call
  end
end