Advertisement
Guest User

Untitled

a guest
Nov 9th, 2016
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.50 KB | None | 0 0
  1. class CommandParser
  2.   def initialize(command)
  3.     @command_name = command
  4.     @arg = []
  5.     @opt_w_p = {}
  6.     @arg_cnt = 0
  7.     @used_args = 0
  8.   end
  9.  
  10.   def argument(name)
  11.     @arg[@arg_cnt] = [Proc.new, name]
  12.     @arg_cnt += 1
  13.   end
  14.  
  15.   def option_with_parameter(short_name, full_name, description, value = true)
  16.     short_name = '-' << short_name
  17.     full_name = '--' << full_name
  18.     @opt_w_p[short_name] = [full_name, description, Proc.new, value]
  19.     @opt_w_p[full_name] = [short_name, description, Proc.new, value]
  20.   end
  21.  
  22.   alias_method :option, :option_with_parameter
  23.  
  24.   def parse(command_runner, argv)
  25.     argv.each do |x|
  26.       unless x.start_with?("-")
  27.         @arg[@used_args][0].call(command_runner, x) && @used_args += 1 && next
  28.       end
  29.       name, param = x.split('=')
  30.       @opt_w_p[name][2].call(command_runner, true) && next unless param
  31.       @opt_w_p[name][2].call(command_runner, param)
  32.     end
  33.   end
  34.  
  35.   def help
  36.     description = "Usage: #{@command_name}"
  37.     @arg.each { |x| description << " [#{x[1]}]" }
  38.     description <<= "\n"
  39.     @opt_w_p.each { |value| description <<= option_definition(value) }
  40.     description
  41.   end
  42.  
  43.   private
  44.  
  45.   def option_definition(value)
  46.     definition = ""
  47.     key, option = value
  48.     if value.first.length <= 2
  49.       definition << "    " << value.first << ", " << @opt_w_p[key][0]
  50.       definition << "=" << option[3] unless option[3] === true
  51.       definition << " " << option[1].to_s << "\n"
  52.     end
  53.     definition
  54.   end
  55. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement