Here is an example of usage:
# General Options module GeneralOptions attr_writer :dryrun ; alias_writer :n, :noharm, :dryrun attr_writer :quiet ; alias_writer :q, :quiet attr_writer :force attr_writer :trace end # Build Subcommand class BuildCommand < Command include GeneralOptions # metadata files attr_writer :file ; alias_writer :f, :file attr_writer :manifest ; alias_writer :m, :manifest def call # do stuf here end end # Box Master Command class BoxCommand < CLI::Command subcommand :build, BuildCommand end BoxCommand.start
Methods
call
new
option_arity
start
subcommand
Classes and Modules
Module CLI::Command::UniversalOptionsAttributes
[R] | arguments | Command Arguments (for single commands). |
[R] | options | Command options. For dispatch commands these are the pre-options. |
Public Class methods
[ + ]
# File lib/more/facets/command.rb, line 190 def initialize(*args) @arguments = [] @options = {} opts, args = *args.partition{ |e| Hash===e } #TEST("options should all be hashes"){ ! opts.all?{ |e| Hash===e } initialize_arguments(*args) initialize_options(*opts) end
[ + ]
# File lib/more/facets/command.rb, line 128 def self.option_arity(arity_hash=nil) @option_arity ||= {} if arity_hash @option_arity.merge!(arity_hash) end @option_arity end
[ + ]
# File lib/more/facets/command.rb, line 138 def self.start(line=nil) cargs = Arguments.new(line || ARGV, option_arity) pre = cargs.preoptions if instance_method(:call).arity == 0 #is_a?(SingleCommand) args, opts = *cargs.parameters new(args, opts).call else subc, args, opts = *cargs.subcommand if self < UniversalOptions new(pre, opts).call(subc, args, opts) else new(pre).call(subc, args, opts) end end end
For dispatchers, this is a convenience method for creating subcommands.
[ + ]
# File lib/more/facets/command.rb, line 165 def self.subcommand(name, command_class, options=nil) options ||= {} if options[:no_merge] file, line = __FILE__, __LINE__+1 code = %{ def #{name}(args, opts) #{command_class}.new(args, opts).call end } else file, line = __FILE__, __LINE__+1 code = %{ def #{name}(args, opts) opts.merge(options) #{command_class}.new(args, opts).call end } end class_eval(code, file, line) end
Public Instance methods
For a single command (ie. a subcommand) override call with arity=0.
[ + ]
# File lib/more/facets/command.rb, line 226 def call(cmd=nil, *args) opts = Hash==args.last ? args.pop : {} #TEST("options should all be hashes"){ ! opts.all?{ |e| Hash===e } #cmd = :default if cmd.nil? if cmd.nil? default else begin # FIXME: rename call to [] ? raise NameError if cmd == 'call' raise NameError unless commands.include?(cmd.to_sym) subcommand = method(cmd) parameters = [args, opts] rescue NameError subcommand = method(:command_missing) parameters = [cmd, args, opts] end if subcommand.arity < 0 subcommand.call(*parameters[0..subcommand.arity]) else subcommand.call(*parameters[0,subcommand.arity]) end end end