Commands in ruby terminal application -
i have written first terminal application in ruby. use optionparser parse options , arguments. want create commands. example:
git add . in above line, add command cannot occur anywhere else after application. how create these.
i appreciate if point me in right direction. however, please not reference gems such commander. know these. want understand how done.
the optionparser's parse! takes array of arguments. default, take argv, can override behaviour so:
basic approach
def build_option_parser(command) # depending on `command`, build parser optionparser.new |opt| # ... end end args = argv command = args.shift # pick , remove first option, validation... @options = build_option_parser(command).parse!(args) # parse rest of advanced approach
instead of build_option_parser method huge case-statement, consider oo approach:
class addcommand attr_reader :options def initialize(args) @options = {} @parser = optionparser.new #... @parser.parse(args) end end class myoptionparser def initialize(command, args) @parser = { 'add' => addcommand, '...' => dotscommand }[command.to_s].new(args) end def options @parser.options end end alternatives
for sure, there exist tons of rubygems (well, 20 in list), take care of problem. i'd mention thor powers, e.g. rails command line tool.
Comments
Post a Comment