module UltraCommandLine module Manager module Processors include UltraCommandLine::Manager::Commands MANDATORY_PROCESSOR_METHODS = %i[check_params execute].freeze def processors(for_command: nil) if for_command.nil? processors_hash.values.inject([]) do |res, value| res.concat value res end .uniq else processors_hash[for_command] end end def register_processor(command_name_or_command, processor) verify_processor_implementation processor if processors.include? processor msg = 'Trying to insert a processor already registered: %s' % [processor.inspect] UltraCommandLine.logger.debug msg end command = command_name_or_command_to_command command_name_or_command processors_hash[command.name] ||= [] processors_hash[command.name] << processor command_name = command.name.empty? ? 'Root' : "#{command.name}" UltraCommandLine.logger.debug "Registered Processor #{processor.inspect} to '#{command_name}' command" end def clear_processors @processors_hash = nil end def processor processor_candidates = processors_hash.fetch(command(cmd_line_args).name, []) .select do |processor| processor.check_params command.cmd_line_args end raise UltraCommandLine::Error, 'No processor found for this command line' if processor_candidates.empty? raise UltraCommandLine::Error, 'Too many possible processors' unless processor_candidates.size == 1 processor_candidates.first end private def command_name_or_command_to_command(command_name_or_command) case command_name_or_command when String command_by_alias command_name_or_command when UltraCommandLine::Commands::SubCommand command_name_or_command else raise UltraCommandLine::Error, "Invalid command or command name: '#{command_name_or_command.inspect}'" end end def verify_processor_implementation(processor) MANDATORY_PROCESSOR_METHODS.each do |method_name| unless processor.respond_to? method_name raise UltraCommandLine::Error, "Invalid processor '#{processor.inspect}' missing method '#{method_name}'!" end end end def processors_hash @processors_hash ||= {} end end end end