Йордан обнови решението на 09.11.2016 10:12 (преди около 8 години)
+class CommandParser
+ attr_reader :help
+ def initialize(command_name)
+ @argument_blocks = []
+ @options_hash = {}
+ @options_w_p_hash = {}
+ @help = "Usage: #{command_name}"
+ end
+
+ def argument(name, &block)
+ @help << " [#{name}]"
+ @argument_blocks << block
+ end
+
+ def argument_call(runner, values)
+ i = 0
+ @argument_blocks.each do |block|
+ block.call(runner, values[i]) if values[i]
+ i += 1
+ end
+ end
+
+ def option(short_name, name, description, &block)
+ @help << "\n -#{short_name}, --#{name} #{description}"
+ @options_hash["-" + short_name] = block
+ @options_hash["--" + name] = block
+ end
+
+ def option_call(runner, values)
+ values.each do |val|
+ @options_hash[val].call(runner, true) if @options_hash.key?(val)
+ end
+ end
+
+ def option_with_parameter(short_name, name, description, val, &block)
+ @help << "\n -#{short_name}, --#{name}=#{val} #{description}"
+ @options_w_p_hash["-" + short_name] = block
+ @options_w_p_hash["--" + name] = block
+ end
+
+ def option_with_parameter_call(runner, values)
+ values.each do |val|
+ key, v = val.split "="
+ @options_w_p_hash[key].call(runner, v) if @options_w_p_hash.key?(key)
+ end
+ end
+
+ def parse(command_runner, argv)
+ @argv_argument = argv.reject { |x| x.start_with? "-" }
+ @argv_opt = argv.select { |x| x.start_with? "-" }
+ @argv_opt = @argv_opt.reject { |x| x.include?("=") }
+ @argv_opt_w_p = argv - @argv_argument - @argv_opt
+ argument_call command_runner, @argv_argument
+ option_call command_runner, @argv_opt
+ option_with_parameter_call command_runner, @argv_opt_w_p
+ end
+end