Sha256: cf112f3fda6b80f8499b6ff86720209d75e88c5d68b1362ce6950fb91c63d9f7

Contents?: true

Size: 1.52 KB

Versions: 3

Compression:

Stored size: 1.52 KB

Contents

module Rack::App::CLI::DefaultCommands::ListCommands
  extend self

  PRESERVED_KEYWORDS = %w[commands help routes irb].freeze

  DEFAULT_COMMANDS = {
    'commands' => 'list all available command',
    'routes' => Rack::App::CLI::DefaultCommands::ShowRoutes.description,
    'irb' => Rack::App::CLI::DefaultCommands::IRB.description
  }.freeze

  class Formatter
    def initialize(known_commands)
      @rjust = known_commands.keys.push(*PRESERVED_KEYWORDS).map(&:to_s).map(&:length).max + 3
    end

    def command_suggestion_line_by(name, desc)
      [name.to_s.rjust(@rjust), desc].join('  ')
    end

    def format(collection_hash)
      collection_hash.to_a.sort_by{ |k, v| k.to_s }.map do |name, desc|
        command_suggestion_line_by(name, desc)
      end.join("\n")
    end
  end

  def get_message(known_commands)
    collection = {}
    add_default_suggestions(collection)
    add_user_defined_commands(known_commands, collection)

    [
      header,
      Formatter.new(known_commands).format(collection)
    ].join("\n")
  end

  protected

  def header
    cmd_file_name = File.basename($PROGRAM_NAME)
    [
      "Usage: #{cmd_file_name} <command> [options] <args>\n\n",
      "Some useful #{cmd_file_name} commands are:"
    ].join("\n")
  end

  def add_default_suggestions(collection)
    collection.merge!(DEFAULT_COMMANDS)
  end

  def add_user_defined_commands(known_commands, collection)
    known_commands.sort_by { |name, _| name.to_s }.each do |name, command|
      collection[name] = command.class.description
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rack-app-7.2.2 lib/rack/app/cli/default_commands/list_commands.rb
rack-app-7.2.1 lib/rack/app/cli/default_commands/list_commands.rb
rack-app-7.2.0 lib/rack/app/cli/default_commands/list_commands.rb