Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class CommandParser
- def initialize(command)
- @command_name = command
- @arg = []
- @opt_w_p = {}
- @arg_cnt = 0
- @used_args = 0
- end
- def argument(name)
- @arg[@arg_cnt] = [Proc.new, name]
- @arg_cnt += 1
- end
- def option_with_parameter(short_name, full_name, description, value = true)
- short_name = '-' << short_name
- full_name = '--' << full_name
- @opt_w_p[short_name] = [full_name, description, Proc.new, value]
- @opt_w_p[full_name] = [short_name, description, Proc.new, value]
- end
- alias_method :option, :option_with_parameter
- def parse(command_runner, argv)
- argv.each do |x|
- unless x.start_with?("-")
- @arg[@used_args][0].call(command_runner, x) && @used_args += 1 && next
- end
- name, param = x.split('=')
- @opt_w_p[name][2].call(command_runner, true) && next unless param
- @opt_w_p[name][2].call(command_runner, param)
- end
- end
- def help
- description = "Usage: #{@command_name}"
- @arg.each { |x| description << " [#{x[1]}]" }
- description <<= "\n"
- @opt_w_p.each { |value| description <<= option_definition(value) }
- description
- end
- private
- def option_definition(value)
- definition = ""
- key, option = value
- if value.first.length <= 2
- definition << " " << value.first << ", " << @opt_w_p[key][0]
- definition << "=" << option[3] unless option[3] === true
- definition << " " << option[1].to_s << "\n"
- end
- definition
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement