Лазар обнови решението на 02.11.2016 11:08 (преди около 8 години)
+class CommandParser
+ def initialize(command_name)
+ @name = command_name
+ @runner = {}
+ @options_with_param = []
+ @options = []
+ @arguments = []
+ end
+
+ def argument(opt)
+ arguments << opt
+ yield runner, opt
+ end
+
+ def option(short, long, descr)
+ options << {short: '-' + short, long: '--' + long, descr: descr}
+ yield runner, true
+ end
+
+ def option_with_parameter(short, long, descr, value)
+ options_with_param << {short: '-' + short, long: '--' + long, descr: descr}
+ yield runner, value
+ end
+
+ def parse(command_runner, argv)
+ runner.keys.each do |value|
+ if argv[0][0] == '-' && !argv[0].nil?
+ command_runner[value] = parse_options(argv[0], value)
+ elsif !argv[0].nil?
+ command_runner[value] = argv.first
+ end
+ argv.shift(1)
+ end
+ command_runner
+ end
+
+ def help
+ result = "Usage: #{name}"
+ arguments.each { |arg| result += " [#{arg}]" }
+ result += "\n"
+ options.each do |opt|
+ result += "\n #{opt[:short]}, #{opt[:long]} #{opt[:descr]}"
+ end
+ options_with_param.each do |opt|
+ result += "\n #{opt[:short]}, #{opt[:long]} #{opt[:descr]}"
+ end
+ result
+ end
+
+ private
+ attr_accessor :runner
+ attr_accessor :options_with_param
+ attr_accessor :options
+ attr_accessor :arguments
+ attr_accessor :name
+ def parse_options(option, value)
+ if option[0] == '-' && option[1] != '-'
+ result = option[2..option.size - 1]
+ elsif option[0] == '-' && option[1] == '-'
+ result = option.split('=')[1]
+ end
+ if result.nil?
+ return runner[value]
+ else
+ return result
+ end
+ end
+end