Sha256: 83008293a6e9c2d473e3e80c7f08ee9a073fccc469200e1d6d6b508a8d734016

Contents?: true

Size: 1.81 KB

Versions: 4

Compression:

Stored size: 1.81 KB

Contents

# frozen_string_literal: true
require 'forwardable'

module Mnemosyne
  module Probes
    class Registration
      extend ::Forwardable

      attr_reader :class_name, :require_paths

      def initialize(class_name, require_paths, probe)
        @class_name = class_name
        @require_paths = Array require_paths
        @probe = probe
      end

      def installable?
        return true unless class_name

        ::Mnemosyne::Probes.class_available? class_name
      end

      delegate install: :@probe
    end

    class << self
      def class_available?(class_name)
        Module.const_get(class_name).is_a? Class
      rescue NameError
        false
      end

      def register(*args)
        registration = Registration.new(*args)

        if registration.installable?
          registration.install
        else
          register_require_hook registration
        end
      end

      def require_hook(name)
        registration = require_hooks[name]
        return unless registration
        return unless registration.installable?

        registration.install

        unregister_require_hook registration
      end

      def register_require_hook(registration)
        registration.require_paths.each do |path|
          require_hooks[path] = registration
        end
      end

      def unregister_require_hook(registration)
        registration.require_paths.each do |path|
          require_hooks.delete path
        end
      end

      private

      def require_hooks
        @require_hooks ||= {}
      end
    end
  end
end

module Kernel
  alias require_without_mn require

  def require(name)
    ret = require_without_mn(name)

    # rubocop:disable Lint/RescueException
    begin
      ::Mnemosyne::Probes.require_hook(name)

      # rubocop:disable Lint/HandleExceptions
    rescue Exception
    end

    ret
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
mnemosyne-ruby-1.0.1 lib/mnemosyne/probes.rb
mnemosyne-ruby-1.0.0 lib/mnemosyne/probes.rb
mnemosyne-ruby-0.2.0 lib/mnemosyne/probes.rb
mnemosyne-ruby-0.1.0 lib/mnemosyne/probes.rb