Class: Commander::Command

Inherits:
Object show all
Defined in:
lib/commander/command.rb

Overview

A single named command belonging to a Commander::Runner: its description, examples, options (parsed via OptionParser), and the handler invoked with the remaining arguments once options have been parsed. Built up via the block yielded by Runner#command, e.g.

command :foo do |c|
c.syntax = 'foo [options]'
c.option '--bar', 'A switch'
c.action { |args, options| ... }
end

Defined Under Namespace

Classes: Options

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Command

Initialize new command with specified name.



63
64
65
66
67
# File 'lib/commander/command.rb', line 63

def initialize(name)
  @name, @examples, @when_called = name.to_s, [], []
  @options, @proxy_options = [], []
  @global_options = []
end

Instance Attribute Details

#descriptionObject

Returns the value of attribute description.



18
19
20
# File 'lib/commander/command.rb', line 18

def description
  @description
end

#examplesObject

Returns the value of attribute examples.



18
19
20
# File 'lib/commander/command.rb', line 18

def examples
  @examples
end

#global_optionsObject (readonly)

Returns the value of attribute global_options.



19
20
21
# File 'lib/commander/command.rb', line 19

def global_options
  @global_options
end

#nameObject

Returns the value of attribute name.



18
19
20
# File 'lib/commander/command.rb', line 18

def name
  @name
end

#optionsObject

Returns the value of attribute options.



18
19
20
# File 'lib/commander/command.rb', line 18

def options
  @options
end

#proxy_optionsObject

Returns the value of attribute proxy_options.



18
19
20
# File 'lib/commander/command.rb', line 18

def proxy_options
  @proxy_options
end

#summaryObject

Returns the value of attribute summary.



18
19
20
# File 'lib/commander/command.rb', line 18

def summary
  @summary
end

#syntaxObject

Returns the value of attribute syntax.



18
19
20
# File 'lib/commander/command.rb', line 18

def syntax
  @syntax
end

Instance Method Details

#call(args = []) ⇒ Object

Call the commands when_called block with args.



198
199
200
201
202
203
204
205
206
207
208
# File 'lib/commander/command.rb', line 198

def call(args = [])
  object, meth = @when_called[0, 2]
  meth ||= :call
  options = proxy_option_struct

  case object
  when Proc then object.call(args, options)
  when Class then meth == :call ? object.new(args, options) : object.new.send(meth, args, options)
  else object&.send(meth, args, options)
  end
end

#example(description, command) ⇒ Object

Add a usage example for this command.

Usage examples are later displayed in help documentation created by the help formatters.

Examples

command :something do |c|
c.example "Should do something", "my_command something"
end


81
82
83
# File 'lib/commander/command.rb', line 81

def example(description, command)
  @examples << [description, command]
end

#inspectObject



230
231
232
# File 'lib/commander/command.rb', line 230

def inspect
  "<Commander::Command:#{name}>"
end

#option(*args, &block) ⇒ Object

Add an option.

Options are parsed via OptionParser so view it for additional usage documentation. A block may optionally be passed to handle the option, otherwise the options struct seen below contains the results of this option. This handles common formats such as:

-h, --help          options.help           # => bool
--[no-]feature      options.feature        # => bool
--large-switch      options.large_switch   # => bool
--file FILE         options.file           # => file passed
--list WORDS        options.list           # => array
--date [DATE]       options.date           # => date or nil when optional argument not set

Examples

command :something do |c|
c.option '--recursive', 'Do something recursively'
c.option '--file FILE', 'Specify a file'
c.option('--info', 'Display info') { puts "handle with block" }
c.option '--[no-]feature', 'With or without feature'
c.option '--list FILES', Array, 'List the files specified'

c.when_called do |args, options|
  do_something_recursively if options.recursive
  do_something_with_file options.file if options.file
end
end

Help Formatters

This method also parses the arguments passed in order to determine which were switches, and which were descriptions for the option which can later be used within help formatters using option and option.

Input Parsing

Since Commander utilizes OptionParser you can pre-parse and evaluate option arguments. Simply require 'optparse/time', or 'optparse/date', as these objects must respond to #parse.

c.option '--time TIME', Time
c.option '--date [DATE]', Date


131
132
133
134
135
136
137
138
139
140
# File 'lib/commander/command.rb', line 131

def option(*args, &block)
  switches, description = Runner.separate_switches_from_description(*args)
  proc = block || option_proc(switches)
  @options << {
    args: args,
    proc: proc,
    switches: switches,
    description: description,
  }
end

#option_proc(switches) ⇒ Object

Option proxy proc used when a block is not explicitly passed via the #option method. This allows commander to auto-populate and work with option values.



226
227
228
# File 'lib/commander/command.rb', line 226

def option_proc(switches)
  ->(value) { proxy_options << [Runner.switch_to_sym(switches.last), value] }
end

#parse_options_and_call_procs(*args) ⇒ Object

Parses options and calls associated procs, returning the arguments remaining.



184
185
186
187
188
189
190
191
192
193
194
# File 'lib/commander/command.rb', line 184

def parse_options_and_call_procs(*args)
  return args if args.empty?

  # empty proxy_options before populating via OptionParser
  # prevents duplication of options if the command is run twice
  proxy_options.clear
  @options.each_with_object(OptionParser.new) do |option, opts|
    opts.on(*option[:args], &option[:proc])
    opts
  end.parse! args
end

#proxy_option_structObject

Creates an Options instance populated with the option values collected by the #option_proc.



213
214
215
216
217
218
219
220
# File 'lib/commander/command.rb', line 213

def proxy_option_struct
  (global_options + proxy_options).each_with_object(Options.new) do |(option, value), options|
    # options that are present will evaluate to true
    value = true if value.nil?
    options.__send__ :"#{option}=", value
    options
  end
end

#run(*args) ⇒ Object

Run the command with args.

  • parses options, call option blocks
  • invokes when_called proc


175
176
177
# File 'lib/commander/command.rb', line 175

def run(*args)
  call parse_options_and_call_procs(*args)
end

#when_called(*args, &block) ⇒ Object Also known as: action

Handle execution of command. The handler may be a class, object, or block (see examples below).

Examples

# Simple block handling
c.when_called do |args, options|
 # do something
end

# Create inst of Something and pass args / options
c.when_called MyLib::Command::Something

# Create inst of Something and use arbitrary method
c.when_called MyLib::Command::Something, :some_method

# Pass an object to handle callback (requires method symbol)
c.when_called SomeObject, :some_method


162
163
164
165
166
# File 'lib/commander/command.rb', line 162

def when_called(*args, &block)
  fail ArgumentError, 'must pass an object, class, or block.' if args.empty? && !block

  @when_called = block ? [block] : args
end