class FiniteMachine::Hooks

A class reponsible for registering callbacks

Attributes

hooks_map[R]

Public Class Methods

new() click to toggle source

Initialize a hooks_map of hooks

@example

Hooks.new

@api public

# 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

Public Instance Methods

[](name)
Alias for: find
clear() click to toggle source

Remove all callbacks

@api public

# File lib/finite_machine/hooks.rb, line 94
def clear
  @hooks_map.clear
end
empty?() click to toggle source

Check if hooks_map has any elements

@return [Boolean]

@api public

# File lib/finite_machine/hooks.rb, line 87
def empty?
  @hooks_map.empty?
end
find(name) click to toggle source

Finds all hooks for the event type

@param [Symbol] name

@example

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

@return [Array]

the transitions matching event name

@api public

# File lib/finite_machine/hooks.rb, line 42
def find(name)
  @hooks_map[name]
end
Also aliased as: []
inspect() click to toggle source

String representation

@return [String]

@api public

# 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) click to toggle source

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

# File lib/finite_machine/hooks.rb, line 62
def register(hook_event, name, callback)
  @hooks_map[hook_event][name] << callback
end
to_s() click to toggle source

String representation

@return [String]

@api public

# 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) click to toggle source

Unregister callback

@param [String] hook_event @param [String] name @param [Proc] callback

@example

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

@return [Hash]

@api public

# File lib/finite_machine/hooks.rb, line 78
def unregister(hook_event, name, callback)
  @hooks_map[hook_event][name].delete(callback)
end