-
Notifications
You must be signed in to change notification settings - Fork 6
/
event_handler.rb
59 lines (46 loc) · 1.3 KB
/
event_handler.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
require 'thread'
require File.join(File.dirname(__FILE__), "ami.rb")
class EventHandler
@@patterns = {}
@@pattern_lock = Mutex.new
PredefinedPatterns = {
:conference_created => {"TODO" => "TODO"}
}
class << self
def clear!
with_lock { @@patterns.clear }
end
def registered_patterns
with_lock { return @@patterns.clone }
end
def handle_event(event)
with_lock {
@@patterns.each_pair do |pattern, block|
case pattern
when :any: block.call(event)
when String
block.call(event) if pattern == event["Action"]
when Hash
block.call(event) if pattern.inject { |boolean,(key,value)| event[key.to_s] == value.to_s ? true : break}
end
end
}
end
def pattern_for_symbol(symbol)
PredefinedPatterns[symbol]
end
protected
def on(pattern, &block)
raise unless block_given?
if pattern.kind_of?(Symbol) && pattern != :any
pattern = pattern_for_symbol pattern
raise "Unrecognized pattern #{pattern.inspect}" unless pattern
end
with_lock { @@patterns[pattern] = block }
end
private
def with_lock(&block)
@@pattern_lock.synchronize(&block)
end
end
end