Добрин обнови решението на 04.11.2016 17:00 (преди около 8 години)
+module ParserHelpers
+ def parse_arguments(command_runner, argv)
+ to_parse_args_index = 0
+ argv.each do |arg|
+ next if arg[0] == '-'
+ @to_parse_args[to_parse_args_index][0].call(command_runner, arg)
+ to_parse_args_index += 1
+ end
+ end
+
+ def parse_options(command_runner, argv)
+ @to_parse_options.each do |crr|
+ if argv.include?("-#{crr[1]}") || argv.include?("--#{crr[2]}")
+ crr[0].call(command_runner, true)
+ end
+ end
+ end
+
+ def parse_options_with_parameters(command_runner, argv)
+ @to_parse_opt_with_param.each do |crr|
+ argv.each do |arg|
+ crr[0].call(command_runner, arg[2..-1]) if crr[1] == arg[1]
+ arg_splited = arg[2..-1].split('=')
+ crr[0].call(command_runner, arg_splited[1]) if crr[2] == arg_splited[0]
+ end
+ end
+ end
+end
+
+class CommandParser
+ include ParserHelpers
+ def initialize(command_name)
+ @command_name = command_name
+ @to_parse_args = []
+ @to_parse_options = []
+ @to_parse_opt_with_param = []
+ end
+
+ def argument(name, &block)
+ @to_parse_args << [block, name]
+
+ end
+
+ def option(short_name, long_name, text, &block)
+ @to_parse_options << [block, short_name, long_name, text]
+ end
+
+ def option_with_parameter(short_name, long_name, text, plholder, &block)
+ @to_parse_opt_with_param << [block, short_name, long_name, text, plholder]
+ end
+
+ def parse(command_runner, argv)
+ parse_arguments(command_runner, argv)
+ parse_options(command_runner, argv)
+ parse_options_with_parameters(command_runner, argv)
+ end
+
+ def help
+ result = "Usage: #{@command_name} "
+ @to_parse_args.each { |crr| result << '[' + crr[1] + ']' }
+ @to_parse_options.each do |crr|
+ result << "\n -#{crr[1]}, --#{crr[2]} #{crr[3]}"
+ end
+ @to_parse_opt_with_param.each do |crr|
+ result << "\n -#{crr[1]}, --#{crr[2]}=#{crr[4]} #{crr[3]}"
+ end
+ result
+ end
+end