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.lazy.map { |opt| opt.name.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
    puts "\t#{comm.help}"
    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 "\t%-#{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(overloaded) ⇒ Object

This will find the appropriate command and execute it.

Parameters:

  • overloaded (String, Array<String>)

    String containing the command to be processed and its arguments

Returns:

  • (Object)

    Result of invoking the command's block



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/filigree/commands.rb', line 46

def call(overloaded)
  split_line =
  if overloaded.is_a?(String)
    overloaded.split
  elsif overloaded.is_a?(Array)
    overloaded
  else
    raise TypeError, "Expected a String or Array of Strings."
  end

  namespace, rest = self.class.get_namespace(split_line)

  if namespace == self.class.commands
    raise CommandNotFoundError, split_line.join(' ')
  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}. " +
          "Expected #{command.action.arity} but got #{rest.length}."
  end
end