Module: Doing::Hooks

Defined in:
lib/doing/hooks.rb

Overview

Hook manager

Constant Summary collapse

DEFAULT_PRIORITY =
20

Class Method Summary collapse

Class Method Details

.insert_hook(event, priority, &block) ⇒ Object



49
50
51
52
# File 'lib/doing/hooks.rb', line 49

def self.insert_hook(event, priority, &block)
  @hook_priority[block] = [-priority, @hook_priority.size]
  @registry[event] << block
end

.priority_value(priority) ⇒ Object

Ensure the priority is a Fixnum



30
31
32
33
34
# File 'lib/doing/hooks.rb', line 30

def self.priority_value(priority)
  return priority if priority.is_a?(Integer)

  PRIORITY_MAP[priority] || DEFAULT_PRIORITY
end

.register(event, priority: DEFAULT_PRIORITY, &block) ⇒ Object

register hook(s) to be called later, public API



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

def self.register(event, priority: DEFAULT_PRIORITY, &block)
  register_one(event, priority_value(priority), &block)
end

.register_one(event, priority, &block) ⇒ Object

register a single hook to be called later, internal API



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/doing/hooks.rb', line 37

def self.register_one(event, priority, &block)
  unless @registry[event]
    raise Doing::Errors::HookUnavailable, "Invalid hook. Doing only supports #{@registry.keys.inspect}"
  end

  raise Doing::Errors::PluginUncallable, 'Hooks must respond to :call' unless block.respond_to? :call

  Doing.logger.debug('Hook Manager:', "Registered #{event} hook") if ENV['DOING_PLUGIN_DEBUG']

  insert_hook event, priority, &block
end

.trigger(event, *args) ⇒ Object



54
55
56
57
58
59
60
61
62
# File 'lib/doing/hooks.rb', line 54

def self.trigger(event, *args)
  hooks = @registry[event]
  return if hooks.nil? || hooks.empty?

  # sort and call hooks according to priority and load order
  hooks.sort_by { |h| @hook_priority[h] }.each do |hook|
    hook.call(*args)
  end
end