Module: Commandant

Defined in:
lib/commandant.rb,
lib/commandant/command.rb

Defined Under Namespace

Classes: Command, UnknownCommand

Constant Summary collapse

COMMANDS =
{}

Class Method Summary collapse

Class Method Details

.add_alias(commands) ⇒ Object

Creates an alias for each given command.

Examples:

alias :br => :branch, :co => :checkout

Parameters:

  • commands (Hash<Symbol => Symbol>)

    the aliases to create ( new name => old name )



31
32
33
34
35
# File 'lib/commandant.rb', line 31

def add_alias(commands)
  commands.each do |new, old|
    Commandant::COMMANDS[new] = Commandant::COMMANDS[old]
  end
end

.call(name, args = nil) ⇒ Object

Call a given command by name

Parameters:

  • name (Symbol)

    the name of the command to be called

  • args (Array) (defaults to: nil)

    the command’s arguments

Raises:



16
17
18
19
# File 'lib/commandant.rb', line 16

def self.call(name, args=nil)
  raise UnknownCommand.new(name) unless COMMANDS[name]
  COMMANDS[name].call(args)
end

.clear!Object

Clears out all defined commands. Primarily useful for testing



22
23
24
# File 'lib/commandant.rb', line 22

def self.clear!
  COMMANDS.clear
end

.command(name, description = nil) {|args| ... } ⇒ Object

Create a new command

Examples:

A Hello World! command

Commandant.command :hello do
  puts "Hello World!"
end

Commandant.run "hello"

A command with arguments

Commandant.command :argprint do |args|
  puts args
end

Commandant.run "argprint foo bizz bazz"

Parameters:

  • name (Symbol)

    the name of the command that is created

  • description (String, nil) (defaults to: nil)

    the command’s description

Yields:

  • The command that will be run

Yield Parameters:

  • args (Array)

    optional: arguments to the command (typically from ARGV)



58
59
60
# File 'lib/commandant.rb', line 58

def command(name, description=nil, &command)
  Command.new(name, description, &command)
end

.run(cmdline = ARGV) ⇒ Object

Runs a given commandline by parsing the command name and arguments. If no command is given, defaults to a command called :main. If that is not present, an UnknownCommand error will be raised.

Parameters:

  • cmdline (Array) (defaults to: ARGV)

    the command line args to be run

Raises:

  • (UnknownCommand)

    command is unknown and no :main command is available



69
70
71
72
73
74
75
76
# File 'lib/commandant.rb', line 69

def run(cmdline=ARGV)
  name, *args = cmdline
  name = name.to_sym if name && COMMANDS[name.to_sym]

  name, *args = :main, name, *args unless COMMANDS[name]

  Commandant.call name, args.compact
end