class Commands::Command

A client command. Contains metadata as well as execution procedure.

Attributes

description[R]

A complete description of the command, suitable for display to the end user.

usage[R]

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

new(usage, description, procedure) click to toggle source

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

exec(client, state, *args) click to toggle source

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
type_of_arg(index) click to toggle source

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

num_args_ok?(num_args) click to toggle source

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