Class: RobustThread

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

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}, &block) ⇒ RobustThread

Create a new RobustThread (see README)



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/robustthread.rb', line 15

def initialize(opts={}, &block)
  self.class.send :init_exit_handler
  args = opts[:args] or []
  @thread = Thread.new(*args) do |*targs|
    begin
      block.call(*targs)
    rescue => e
      @exception = e
      self.class.send :handle_exception, e
    end
    self.class.log "#{self.label.inspect} exited cleanly"
  end
  self.label = opts[:label] || @thread.inspect
  self.class.group << self
end

Class Attribute Details

.exit_handler_initializedObject

Returns the value of attribute exit_handler_initialized.



33
34
35
# File 'lib/robustthread.rb', line 33

def exit_handler_initialized
  @exit_handler_initialized
end

.loggerObject

Logger object (see README)



36
37
38
# File 'lib/robustthread.rb', line 36

def logger
  @logger
end

.say_goodnightObject

Returns the value of attribute say_goodnight.



33
34
35
# File 'lib/robustthread.rb', line 33

def say_goodnight
  @say_goodnight
end

Instance Attribute Details

#exceptionObject (readonly)

If the Thread takes a poopie…



10
11
12
# File 'lib/robustthread.rb', line 10

def exception
  @exception
end

#labelObject

An identifier



12
13
14
# File 'lib/robustthread.rb', line 12

def label
  @label
end

#threadObject (readonly)

The Thread object, brah



8
9
10
# File 'lib/robustthread.rb', line 8

def thread
  @thread
end

Class Method Details

.exception_handler(&block) ⇒ Object

Set exception handler



63
64
65
66
67
68
# File 'lib/robustthread.rb', line 63

def exception_handler(&block)
  unless block.arity == 1
    raise ArgumentError, "Bad arity for exception handler. It may only accept a single argument"
  end
  @exception_handler = block
end

.groupObject

The collection of RobustThread objects



46
47
48
# File 'lib/robustthread.rb', line 46

def group
  @group ||= [] 
end

.log(msg, level = :info) ⇒ Object

Simple log interface



41
42
43
# File 'lib/robustthread.rb', line 41

def log(msg, level=:info)
  self.logger.send level, "#{self}: " + msg
end

.loop(opts = {}, &block) ⇒ Object

Loop an activity and exit it cleanly (see README)



51
52
53
54
55
56
57
58
59
60
# File 'lib/robustthread.rb', line 51

def loop(opts={}, &block)
  sleep_seconds = opts.delete(:seconds) || 2
  self.new(opts) do |*args|
    Kernel.loop do
      break if self.say_goodnight
      block.call(*args)
      sleep sleep_seconds
    end
  end
end