Class: Multitrap::Trap

Inherits:
Object
  • Object
show all
Defined in:
lib/multitrap.rb

Constant Summary collapse

RESERVED_SIGNALS =
{
  'BUS' => 10,
  'SEGV' => 11,
  'ILL' => 4,
  'FPE' => 8,
  'VTALRM' => 26
}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(old_trap) ⇒ Trap

Returns a new instance of Trap.



19
20
21
22
23
# File 'lib/multitrap.rb', line 19

def initialize(old_trap)
  @old_trap = old_trap
  @traps = {}
  @mutex = Mutex.new
end

Class Method Details

.trap(sig, prc, old_trap, &block) ⇒ Object



14
15
16
17
# File 'lib/multitrap.rb', line 14

def self.trap(sig, prc, old_trap, &block)
  @multitrap ||= self.new(old_trap)
  @multitrap.add_trap(sig, prc, &block)
end

Instance Method Details

#add_trap(sig, prc, &block) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/multitrap.rb', line 33

def add_trap(sig, prc, &block)
  if RESERVED_SIGNALS.key?(sig)
    raise ArgumentError, "can't trap reserved signal SIG#{sig}"
  end

  unless Signal.list.key?(sig)
    raise ArgumentError, "unsupported signal SIG#{sig}"
  end

  prc ||= block

  if prc.nil?
    raise ArgumentError, "tried to create Proc object without a block"
  end

  @traps[sig] ||= []

  @mutex.synchronize do
    if recursion?
      @traps[sig].pop
    else
      @traps[sig].push(prc || block)
    end
  end

  @old_trap.call(sig) do
    @traps[sig].each do |trap_handler|
      trap_handler.call(Signal.list[sig])
    end
  end

  @traps
end

#recursion?Boolean

Returns:

  • (Boolean)


25
26
27
28
29
30
31
# File 'lib/multitrap.rb', line 25

def recursion?
  frame = caller.find do |f|
    f =~ %r{multitrap/lib/multitrap\.rb.+`block in add_trap'}
  end

  true if frame
end