Даниела обнови решението на 07.11.2016 16:36 (преди около 8 години)
+class CommandParser
+ def initialize(command_name)
+ @command_name = command_name
+ @arguments = []
+ @options = []
+ @option_with_parameters = []
+ end
+
+ def argument(name, &block)
+ @arguments.push(Argument.new(name, block))
+ end
+
+ def option(short_name, full_name, description, &block)
+ @options.push(Option.new(short_name, full_name, description, block))
+ end
+
+ def option_with_parameter(short_name, full_name, description, holder, &block)
+ @option_with_parameters.push(OptionWithParameter.new(
+ short_name,
+ full_name,
+ description,
+ holder,
+ block
+ )
+ )
+ end
+
+ def parse(command_runner, argv)
+ @arguments.each_with_index { |n, i| n.parse(command_runner, argv[i]) }
+ @options.each { |n| n.parse(command_runner, argv) }
+ @option_with_parameters.each { |n| n.parse(command_runner, argv) }
+ end
+
+ def help
+ message = ''
+ if @arguments
+ message << 'Usage: ' + @command_name
+ @arguments.each { |x| x.help(message) }
+ end
+ @options.each { |x| x.help(message) }
+ @option_with_parameters.each { |x| x.help(message) }
+ message
+ end
+end
+
+class Argument < CommandParser
+ def initialize(name, block)
+ @name = name
+ @block = block
+ end
+
+ def parse(command_runner, argv)
+ @block.call(command_runner, argv)
+ end
+
+ def help(message)
+ message << ' [' + @name + ']'
+ end
+end
+
+class Option < CommandParser
+ def initialize(short_name, full_name, description, block)
+ @short_name = short_name
+ @full_name = full_name
+ @description = description
+ @block = block
+ end
+
+ def parse(command_runner, argv)
+ argv.any? { |x| x[1..-1] == @short_name || x[2..-1] == @full_name }
+ @block.call(command_runner, true)
+ end
+
+ def help(message)
+ message << "\n" + ' -' +
+ @short_name + ', --' +
+ @full_name + ' ' + @description
+ end
+end
+
+class OptionWithParameter < CommandParser
+ def initialize(short_name, full_name, description, holder, block)
+ @short_name = short_name
+ @full_name = full_name
+ @description = description
+ @holder = holder
+ @block = block
+ end
+
+ def parse(command_runner, argv)
+ if argv.any? { |x| x[2..(@full_name.size + 1)] == @full_name }
+ @block.call(command_runner, argv[0][(3 + @full_name.size)..-1])
+ elsif argv.any? { |x| x[1] == @short_name }
+ @block.call(command_runner, argv[0][2..-1])
+ end
+ end
+
+ def help(message)
+ message << "\n" + ' -' +
+ @short_name + ', --' +
+ @full_name + '=' + @holder + ' ' + @description
+ end
+end