Sha256: 08c1970d3b3898bc695ffac76b2945674bb3a6f74539526bdca46d9d5f2876a2

Contents?: true

Size: 1.39 KB

Versions: 3

Compression:

Stored size: 1.39 KB

Contents

# frozen_string_literal: true
module Ragent
  class Commands
    include Ragent::Logging

    def initialize(ragent)
      @ragent = ragent
      @commands = {}
      add_help_command
    end

    def add(command)
      if command.sub?
        @commands[command.main] ||= {}
        @commands[command.main][command.sub] = command
      else
        @commands[command.main] ||= command
      end
      info "registered command: #{command.help}"
    end

    def lookup(main, sub, options)
      debug "checkig command: #{main},#{sub},#{options}"
      cmd = @commands[main]
      if cmd

        if cmd.is_a?(Hash) && sub
          sub_cmd = @commands[main][sub]
          if sub_cmd
            debug "command found (#{main},#{sub})"
          else
            debug "command not found (#{main},#{sub})"
          end
          return sub_cmd
        else
          debug "command found (#{main})"
          return cmd
        end
      else
        debug 'command not found'
      end
      nil
    end

    private

    def help_command(_options = {})
      @commands.values.map do |subs|
        if subs.is_a?(Hash)
          subs.values.map(&:help)
        else
          subs.help
        end
      end.flatten.join("\n")
    end

    def add_help_command
      add(Ragent::Command.new(main: 'help',
                              recipient: self,
                              method: :help_command))
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ragent-0.0.6 lib/ragent/commands.rb
ragent-0.0.5 lib/ragent/commands.rb
ragent-0.0.4 lib/ragent/commands.rb