Class: Evilution::Hooks

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

Defined Under Namespace

Classes: Loader, Registry

Constant Summary collapse

EVENTS =
%i[
  worker_process_start
  mutation_insert_pre
  mutation_insert_post
  setup_integration_pre
  setup_integration_post
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHooks

Returns a new instance of Hooks.



12
13
14
# File 'lib/evilution/hooks.rb', line 12

def initialize
  @handlers = EVENTS.to_h { |event| [event, []] }
end

Class Method Details

.from_config(config_hooks) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/evilution/hooks.rb', line 43

def self.from_config(config_hooks)
  hooks = new
  return hooks if config_hooks.nil? || config_hooks.empty?

  config_hooks.each do |event, callables|
    Array(callables).each { |callable| hooks.register(event) { |payload| callable.call(payload) } }
  end
  hooks
end

Instance Method Details

#clear(event = nil) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/evilution/hooks.rb', line 29

def clear(event = nil)
  if event
    validate_event!(event)
    @handlers[event].clear
  else
    @handlers.each_value(&:clear)
  end
end

#fire(event, **payload) ⇒ Object



24
25
26
27
# File 'lib/evilution/hooks.rb', line 24

def fire(event, **payload)
  validate_event!(event)
  @handlers[event].each { |handler| handler.call(payload) }
end

#handlers_for(event) ⇒ Object



38
39
40
41
# File 'lib/evilution/hooks.rb', line 38

def handlers_for(event)
  validate_event!(event)
  @handlers[event].dup
end

#register(event, &block) ⇒ Object

Raises:

  • (ArgumentError)


16
17
18
19
20
21
22
# File 'lib/evilution/hooks.rb', line 16

def register(event, &block)
  validate_event!(event)
  raise ArgumentError, "a block must be provided when registering handler for #{event}" unless block

  @handlers[event] << block
  self
end