finish lifecycle conditions handling and add flapper condition
[god.git] / lib / god / condition.rb
blob8af078d977b4a20dbf614a4ed0ef08d3c8f15e81
1 module God
2   
3   class Condition < Behavior
4     attr_accessor :transition
5     
6     # Generate a Condition of the given kind. The proper class if found by camel casing the
7     # kind (which is given as an underscored symbol).
8     #   +kind+ is the underscored symbol representing the class (e.g. foo_bar for God::Conditions::FooBar)
9     def self.generate(kind, watch)
10       sym = kind.to_s.capitalize.gsub(/_(.)/){$1.upcase}.intern
11       c = God::Conditions.const_get(sym).new
12       
13       unless c.kind_of?(PollCondition) || c.kind_of?(EventCondition) || c.kind_of?(TriggerCondition)
14         abort "Condition '#{c.class.name}' must subclass either God::PollCondition or God::EventCondition" 
15       end
16       
17       c.watch = watch
18       c
19     rescue NameError
20       raise NoSuchConditionError.new("No Condition found with the class name God::Conditions::#{sym}")
21     end
22   end
23   
24   class PollCondition < Condition
25     # all poll conditions can specify a poll interval 
26     attr_accessor :interval
27     
28     # Override this method in your Conditions (optional)
29     def before
30     end
31     
32     # Override this method in your Conditions (mandatory)
33     #
34     # Return true if the test passes (everything is ok)
35     # Return false otherwise
36     def test
37       raise AbstractMethodNotOverriddenError.new("PollCondition#test must be overridden in subclasses")
38     end
39     
40     # Override this method in your Conditions (optional)
41     def after
42     end
43   end
44   
45   class EventCondition < Condition
46     def register
47       raise AbstractMethodNotOverriddenError.new("EventCondition#register must be overridden in subclasses")
48     end
49     
50     def deregister
51       raise AbstractMethodNotOverriddenError.new("EventCondition#deregister must be overridden in subclasses")
52     end
53   end
54   
55   class TriggerCondition < Condition
56     def process(event, payload)
57       raise AbstractMethodNotOverriddenError.new("TriggerCondition#process must be overridden in subclasses")
58     end
59     
60     def trigger
61       Hub.trigger(self)
62     end
63     
64     def register
65       Trigger.register(self)
66     end
67     
68     def deregister
69       Trigger.deregister(self)
70     end
71   end
72   
73 end