class Commander::Command
def call(args = [])
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
def example(description, command)
def example(description, command) @examples << [description, command] end
def initialize(name)
def initialize(name) @name, @examples, @when_called = name.to_s, [], [] @options, @proxy_options = [], [] @global_options = [] end
def inspect
def inspect "<Commander::Command:#{name}>" end
def option(*args, &block)
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
def option_proc(switches)
def option_proc(switches) ->(value) { proxy_options << [Runner.switch_to_sym(switches.last), value] } end
def parse_options_and_call_procs(*args)
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
def proxy_option_struct
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
def run(*args)
def run(*args) call parse_options_and_call_procs(*args) end
def when_called(*args, &block)
def when_called(*args, &block) fail ArgumentError, 'must pass an object, class, or block.' if args.empty? && !block @when_called = block ? [block] : args end