class Commands::Command
A client command. Contains metadata as well as execution procedure.
Attributes
A complete description of the command, suitable for display to the end user.
A String
specifying the usage of the command in the style of a man page synopsis. Optional arguments are enclosed in brackets; varargs-style arguments are suffixed with an ellipsis.
Public Class Methods
Create a new Command
with the given metadata and a Proc
specifying its behavior. The Proc
will receive three arguments: the DropboxClient
, the State
, and an Array
of command-line arguments.
# File lib/droxi/commands.rb, line 25 def initialize(usage, description, procedure) @usage = usage @description = description.squeeze(' ') @procedure = procedure end
Public Instance Methods
Attempt to execute the Command
. Raises a UsageError
if an invalid number of command-line arguments is given.
# File lib/droxi/commands.rb, line 33 def exec(client, state, *args) fail UsageError, @usage unless num_args_ok?(args.size) @procedure.yield(client, state, args) end
Return a String
describing the type of argument at the given index. If the index is out of range, return the type of the final argument. If the Command
takes no arguments, return nil
.
# File lib/droxi/commands.rb, line 41 def type_of_arg(index) args = @usage.gsub(/\[-.+?\]/, '').split.drop(1) return nil if args.empty? index = [index, args.size - 1].min args[index].tr('[].', '') end
Private Instance Methods
Return true
if the given number of arguments is acceptable for the command, false
otherwise.
# File lib/droxi/commands.rb, line 52 def num_args_ok?(num_args) args = @usage.split.drop(1) min_args = args.count { |arg| !arg[/[\[\]]/] } max_args = if args.any? { |arg| arg.end_with?('...') } num_args else args.size end (min_args..max_args).include?(num_args) end