Class: FiniteMachine::Hooks

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

Overview

A class reponsible for registering callbacks

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHooks

Initialize a hooks_map of hooks

Examples:

Hooks.new


19
20
21
22
23
24
25
26
27
28
29
# File 'lib/finite_machine/hooks.rb', line 19

def initialize
  @hooks_map = Concurrent::Map.new do |events_hash, hook_event|
    events_hash.compute_if_absent(hook_event) do
      Concurrent::Map.new do |state_hash, name|
        state_hash.compute_if_absent(name) do
          Concurrent::Array.new
        end
      end
    end
  end
end

Instance Attribute Details

#hooks_mapObject (readonly)

Returns the value of attribute hooks_map.



11
12
13
# File 'lib/finite_machine/hooks.rb', line 11

def hooks_map
  @hooks_map
end

Instance Method Details

#clearObject

Remove all callbacks



94
95
96
# File 'lib/finite_machine/hooks.rb', line 94

def clear
  @hooks_map.clear
end

#empty?Boolean

Check if hooks_map has any elements

Returns:

  • (Boolean)


87
88
89
# File 'lib/finite_machine/hooks.rb', line 87

def empty?
  @hooks_map.empty?
end

#find(name) ⇒ Array[Transition] Also known as: []

Finds all hooks for the event type

Examples:

hooks[HookEvent::Enter][:go] # => [-> { }]

Parameters:

  • name (Symbol)

Returns:

  • (Array[Transition])

    the transitions matching event name



42
43
44
# File 'lib/finite_machine/hooks.rb', line 42

def find(name)
  @hooks_map[name]
end

#inspectString

String representation

Returns:

  • (String)


119
120
121
# File 'lib/finite_machine/hooks.rb', line 119

def inspect
  "<##{self.class}:0x#{object_id.to_s(16)} @hooks_map=#{self}>"
end

#register(hook_event, name, callback) ⇒ Hash

Register callback

Examples:

hooks.register HookEvent::Enter, :green do ... end
hooks.register HookEvent::Before, any_state do ... end

Parameters:

  • hook_event (String)
  • name (String)
  • callback (Proc)

Returns:

  • (Hash)


62
63
64
# File 'lib/finite_machine/hooks.rb', line 62

def register(hook_event, name, callback)
  @hooks_map[hook_event][name] << callback
end

#to_sString

String representation

Returns:

  • (String)


103
104
105
106
107
108
109
110
111
112
# File 'lib/finite_machine/hooks.rb', line 103

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

#unregister(hook_event, name, callback) ⇒ Hash

Unregister callback

Examples:

hooks.unregister HookEvent::Enter, :green do ... end

Parameters:

  • hook_event (String)
  • name (String)
  • callback (Proc)

Returns:

  • (Hash)


78
79
80
# File 'lib/finite_machine/hooks.rb', line 78

def unregister(hook_event, name, callback)
  @hooks_map[hook_event][name].delete(callback)
end