Class: Clin::CommandDispatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/clin/command_dispatcher.rb

Overview

Class charge dispatching the CL to the right command

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*commands) ⇒ CommandDispatcher

Create a new command dispatcher.

Parameters:

  • commands (Array<Clin::Command.class>)

    List of commands that can be dispatched. If commands is nil it will get all the subclass of Clin::Command loaded.



12
13
14
# File 'lib/clin/command_dispatcher.rb', line 12

def initialize(*commands)
  @commands = commands.empty? ? Clin::Command.subcommands : commands.flatten
end

Instance Attribute Details

#commandsObject

Contains the list of commands the dispatch will test.



7
8
9
# File 'lib/clin/command_dispatcher.rb', line 7

def commands
  @commands
end

Class Method Details

.parse(argv = ARGV) ⇒ Object

Helper method to parse against all the commands

See Also:



36
37
38
# File 'lib/clin/command_dispatcher.rb', line 36

def self.parse(argv = ARGV)
  Clin::CommandDispatcher.new.parse(argv)
end

Instance Method Details

#help_messageString

Generate the help message for this dispatcher

Returns:

  • (String)


42
43
44
45
46
47
48
# File 'lib/clin/command_dispatcher.rb', line 42

def help_message
  message = "Usage:\n"
  commands.each do |command|
    message << "\t#{command.usage}\n"
  end
  message
end

#parse(argv = ARGV) ⇒ Clin::Command

Parse the command line using the given arguments It will return the newly initialized command with the arguments if there is a match Otherwise will fail and display the help message

Parameters:

  • argv (Array<String>) (defaults to: ARGV)

    Arguments

Returns:



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/clin/command_dispatcher.rb', line 21

def parse(argv = ARGV)
  errors = 0
  argv = Shellwords.split(argv) if argv.is_a? String
  @commands.each do |cmd|
    begin
      return cmd.parse(argv, fallback_help: false)
    rescue Clin::ArgumentError
      errors += 1
    end
  end
  fail Clin::HelpError, help_message
end