Module: Filigree::Commands

Includes:
ClassMethodsModule
Defined in:
lib/filigree/commands.rb

Defined Under Namespace

Modules: ClassMethods Classes: Command

Constant Summary collapse

HELP_COMMAND =

The default help command. This can be added to your class via add_command.

Command.new('help', 'Prints this help message.', [], nil, Proc.new do
  puts 'Usage: <command> [options] <args>'
  puts
  puts 'Commands:'

  comm_list = self.class.command_list

  sorted_comm_list = comm_list.sort { |a, b| a.name <=> b.name }
  max_length       = comm_list.map(:name).inject(0) { |max, str| max <= str.length ? str.length : max }


  sorted_comm_list.each do |comm|
    printf "  % #{max_length}s", comm.name
  
    if comm.config
      print ' [options]'
    end
  
    puts comm.param_help.inject('') { |str, pair| str << " <#{pair.first}>" }
  
    if comm.config
      options = comm.config.options_long.values.sort { |a, b| a.long <=> b.long }
      puts Filigree::Configuration::Option.to_s(options, max_length + 4)
    end
  
    puts
  
    if !comm.param_help.empty?
      max_param_len = comm.param_help.inject(0) do |max, pair|
        param_len = pair.first.to_s.length
        max <=  param_len ? param_len : max
      end
    
      segment_indent = max_param_len + 8
      comm.param_help.each do |name, help|
        printf "     %-#{max_param_len}s - %s\n", name, help.segment(segment_indent)
      end
    end
  end
end)

Instance Method Summary collapse

Methods included from ClassMethodsModule

included

Instance Method Details

#call(line) ⇒ Object

This will find the appropriate command and execute it.

Parameters:

  • line (String)

    String containing the command to be processed and its arguments

Returns:

  • (Object)

    Result of invoking the command’s block



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/filigree/commands.rb', line 44

def call(line)
  namespace, rest = self.class.get_namespace(line.split)

  if namespace == self.class.commands
    raise CommandNotFoundError, line
  end

  command = namespace[:nil]

  action = 
  if command.config
    conf_obj = command.config.new(rest)
    rest     = conf_obj.rest
  
    -> (*args) { conf_obj.instance_exec(*args, &command.action) }
  else
    command.action
  end

  if command.action.arity < 0 or command.action.arity == rest.length
    self.instance_exec(*rest, &action)
  else
    raise ArgumentError, "Wrong number of arguments for command: #{command.name}."
  end
end