implemented state based lifecycle
[god.git] / lib / god / hub.rb
blob16163c9c538ac139075e7494dd30d85c0e49bfdf
1 module God
2   
3   class Hub
4     @@directory = {}
5     
6     def self.attach(condition, metric)
7       @@directory[condition] = metric
8       
9       if condition.kind_of?(PollCondition)
10         Timer.get.schedule(condition, 0)
11       else
12         condition.register
13       end
14     end
15     
16     def self.detach(condition)
17       @@directory.delete(condition)
18     end
19     
20     def self.trigger(condition)
21       if condition.kind_of?(PollCondition)
22         self.handle_poll(condition)
23       else
24         puts 'event!'
25       end
26     end
27     
28     def self.handle_poll(condition)
29       Thread.new do
30         metric = @@directory[condition]
31         watch = metric.watch
32         
33         watch.mutex.synchronize do
34           result = condition.test
35           
36           puts watch.name + ' ' + condition.class.name + " [#{result}]"
37           
38           condition.after
39           
40           p metric.destination
41           
42           if dest = metric.destination[result]
43             watch.move(dest)
44           else
45             # reschedule
46             puts 'reschedule'
47             Timer.get.schedule(c)
48           end
49         end
50       end
51     end
52   end
53   
54 end