# encoding: utf-8 require 'fedux_org_stdlib/plugins/no_plugin' require 'fedux_org_stdlib/plugins/plugin' require_library %w{ json active_support/core_ext/string/inflections } module FeduxOrgStdlib module Plugins # Plugin Manager # # Make sure you've got a class method `.plugin_prefix` on your main module # # @example # # -- main.rb -- # # main module # module YourApplication # # The manager # @plugin_manager = PluginManager.new # # # This regex depends on your application's plugins file system structure # @plugin_prefix = Regexp.new("^#{self.name.underscore.gsub(/\//, '-')}-") # # class << self # attr_reader :plugin_prefix, :plugin_manager # # def load_plugins # self.plugin_manager.locate_plugins # self.plugin_manager.load_plugins # end # end # end # # At some place you need to load your plugins. # # @example # # # -- runner.rb -- # # YourApplication.load_plugins # class PluginManager private attr_reader :plugins public def initialize(plugins: []) @plugins = plugins end # Find all installed plugins and store them in an internal array. def locate_plugins Gem.refresh (Gem::Specification.respond_to?(:each) ? Gem::Specification : Gem.source_index.find_name('')).each do |gem| next if gem.name !~ plugin_prefix plugin_name = gem.name.split('-', 2).last @plugins << Plugin.new(plugin_name, gem.name, gem, true) if !gem_located?(gem.name) end @plugins end # @return [Hash] A hash with all plugin names (minus the '-') as # keys and Plugin objects as values. def plugins h = Hash.new { |_, key| NoPlugin.new(key) } @plugins.each do |plugin| h[plugin.name] = plugin end h end # Require all enabled plugins, disabled plugins are skipped. def load_plugins @plugins.each do |plugin| plugin.activate! if plugin.enabled? end end private def gem_located?(gem_name) @plugins.any? { |plugin| plugin.gem_name == gem_name } end def plugin_prefix module_name = if self.class.name.deconstantize.blank? self.class.name else self.class.name.deconstantize end module_name.constantize.plugin_prefix end end end end