Sha256: 4eadffe009496b7d972d7941e9d46cc3fdd7eb1639875dd8e3aacb45e21be6fd

Contents?: true

Size: 1.54 KB

Versions: 25

Compression:

Stored size: 1.54 KB

Contents

# frozen_string_literal: true

module Mutant
  class Hooks
    include Adamantium, Concord::Public.new(:map)

    DEFAULTS = %i[
      env_infection_pre
      env_infection_post
      mutation_insert_post
      mutation_insert_pre
    ].product([EMPTY_ARRAY]).to_h.transform_values(&:freeze).freeze

    MESSAGE = 'Unknown hook %s'

    private_constant(*constants(false))

    class UnknownHook < RuntimeError; end

    def self.assert_name(name)
      fail UnknownHook, MESSAGE % name.inspect unless DEFAULTS.key?(name)
      self
    end

    def self.empty
      new(DEFAULTS)
    end

    def merge(other)
      self.class.new(
        other.map.merge(map) { |_key, new, old| (old + new).freeze }.freeze
      )
    end

    def run(name, payload)
      Hooks.assert_name(name)

      map.fetch(name).each { |block| block.call(payload) }

      self
    end

    class Builder
      def initialize
        @map = DEFAULTS.transform_values(&:dup)
      end

      def register(name, &block)
        Hooks.assert_name(name)

        @map.fetch(name) << block

        self
      end

      def to_hooks
        Hooks.new(@map.transform_values(&:freeze).freeze)
      end
    end # Builder

    # rubocop:disable Security/Eval
    def self.load_pathname(pathname)
      hooks = Builder.new

      binding.eval(pathname.read, pathname.to_s)

      hooks.to_hooks
    end
    # rubocop:enable Security/Eval

    def self.load_config(config)
      config.hooks.reduce(empty) do |current, path|
        current.merge(load_pathname(path))
      end
    end
  end # Hooks
end # Mutant

Version data entries

25 entries across 25 versions & 1 rubygems

Version Path
mutant-0.11.18 lib/mutant/hooks.rb
mutant-0.11.17 lib/mutant/hooks.rb
mutant-0.11.16 lib/mutant/hooks.rb
mutant-0.11.15 lib/mutant/hooks.rb
mutant-0.11.14 lib/mutant/hooks.rb
mutant-0.11.13 lib/mutant/hooks.rb
mutant-0.11.12 lib/mutant/hooks.rb
mutant-0.11.11 lib/mutant/hooks.rb
mutant-0.11.10 lib/mutant/hooks.rb
mutant-0.11.9 lib/mutant/hooks.rb
mutant-0.11.8 lib/mutant/hooks.rb
mutant-0.11.7 lib/mutant/hooks.rb
mutant-0.11.6 lib/mutant/hooks.rb
mutant-0.11.5 lib/mutant/hooks.rb
mutant-0.11.4 lib/mutant/hooks.rb
mutant-0.11.3 lib/mutant/hooks.rb
mutant-0.11.2 lib/mutant/hooks.rb
mutant-0.11.1 lib/mutant/hooks.rb
mutant-0.11.0 lib/mutant/hooks.rb
mutant-0.10.35 lib/mutant/hooks.rb