Sha256: e5018e991c352b9a246164398919d5af8109bb0ed346d5ced3ce68e8b2de3026

Contents?: true

Size: 1.61 KB

Versions: 33

Compression:

Stored size: 1.61 KB

Contents

# frozen_string_literal: true

module Doing
  # Hook manager
  module Hooks
    DEFAULT_PRIORITY = 20

    @registry = {
      post_config: [],
      post_local_config: [],
      post_read: [],
      pre_write: [],
      post_write: []
    }

    # map of all hooks and their priorities
    @hook_priority = {}

    # register hook(s) to be called later, public API
    def self.register(event, priority: DEFAULT_PRIORITY, &block)
      register_one(event, priority_value(priority), &block)
    end

    # Ensure the priority is a Fixnum
    def self.priority_value(priority)
      return priority if priority.is_a?(Integer)

      PRIORITY_MAP[priority] || DEFAULT_PRIORITY
    end

    # register a single hook to be called later, internal API
    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

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

    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
  end
end

Version data entries

33 entries across 33 versions & 1 rubygems

Version Path
doing-2.1.10 lib/doing/hooks.rb
doing-2.1.9 lib/doing/hooks.rb
doing-2.1.8 lib/doing/hooks.rb
doing-2.1.7 lib/doing/hooks.rb
doing-2.1.6 lib/doing/hooks.rb
doing-2.1.6pre lib/doing/hooks.rb
doing-2.1.5pre lib/doing/hooks.rb
doing-2.1.4pre lib/doing/hooks.rb
doing-2.1.3 lib/doing/hooks.rb
doing-2.1.2pre lib/doing/hooks.rb
doing-2.1.1pre lib/doing/hooks.rb
doing-2.1.0pre lib/doing/hooks.rb
doing-2.0.25 lib/doing/hooks.rb
doing-2.0.24 lib/doing/hooks.rb
doing-2.0.23 lib/doing/hooks.rb
doing-2.0.22 lib/doing/hooks.rb
doing-2.0.21 lib/doing/hooks.rb
doing-2.0.20 lib/doing/hooks.rb
doing-2.0.19 lib/doing/hooks.rb
doing-2.0.18 lib/doing/hooks.rb