forked from piotrmurach/finite_machine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hooks.rb
118 lines (107 loc) · 2.41 KB
/
hooks.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# frozen_string_literal: true
require "concurrent/map"
require_relative "hook_event"
module FiniteMachine
# A class reponsible for registering callbacks
class Hooks
attr_reader :hooks_map
# Initialize a hooks_map of hooks
#
# @example
# Hoosk.new(machine)
#
# @api public
def initialize
@hooks_map = Concurrent::Map.new do |events_hash, hook_event|
events_hash[hook_event] = Concurrent::Map.new do |state_hash, name|
state_hash.compute_if_absent(name) { [] }
end
end
end
# Finds all hooks for the event type
#
# @param [Symbol] name
#
# @example
# hooks[HookEvent::Enter][:go] # => [-> { }]
#
# @return [Array[Transition]]
# the transitions matching event name
#
# @api public
def find(name)
@hooks_map[name]
end
alias [] find
# Register callback
#
# @param [String] hook_event
# @param [String] name
# @param [Proc] callback
#
# @example
# hooks.register HookEvent::Enter, :green do ... end
#
# @example
# hooks.register HookEvent::Before, any_state do ... end
#
# @return [Hash]
#
# @api public
def register(hook_event, name, callback)
@hooks_map[hook_event][name] << callback
end
# Unregister callback
#
# @param [String] hook_event
# @param [String] name
# @param [Proc] callback
#
# @example
# hooks.unregister HookEvent::Enter, :green do ... end
#
# @return [Hash]
#
# @api public
def unregister(hook_event, name, callback)
@hooks_map[hook_event][name].delete(callback)
end
# Check if hooks_map has any elements
#
# @return [Boolean]
#
# @api public
def empty?
@hooks_map.empty?
end
# Remove all callbacks
#
# @api public
def clear
@hooks_map.clear
end
# String representation
#
# @return [String]
#
# @api public
def to_s
hash = {}
@hooks_map.each_pair do |hook_event, nested_hash|
hash[hook_event] = {}
nested_hash.each_pair do |name, callbacks|
hash[hook_event][name] = callbacks
end
end
hash.to_s
end
# String representation
#
# @return [String]
#
# @api public
def inspect
"<##{self.class}:0x#{object_id.to_s(16)} @hooks_map=#{self}>"
end
end # Hooks
end # FiniteMachine