This is a convenience method that properly handles duping the originally argv array so that it is not destroyed. This method will also automatically detect "-h" and "--help" and print help. And if any invalid options are detected, the help will be printed, as well @param [Object, nil] opts An instance of OptionParse to parse against, defaults to a new OptionParse instance @param [Array, nil] arg
(opts=nil, argv=nil)
| 227 | # @return[Array, nil] If this method returns `nil`, then you should assume that help was printed and parsing failed |
| 228 | # |
| 229 | def parse_options(opts=nil, argv=nil) |
| 230 | # Creating a shallow copy of the arguments so the OptionParser |
| 231 | # doesn't destroy the originals. |
| 232 | argv ||= $argv.dup |
| 233 | |
| 234 | # Default opts to a blank optionparser if none is given |
| 235 | opts ||= OptionParser.new |
| 236 | |
| 237 | # Add the help option, which must be on every command. |
| 238 | opts.on_tail('-h', '--help', 'Print this help') do |
| 239 | safe_puts(opts.help) |
| 240 | return nil |
| 241 | end |
| 242 | |
| 243 | opts.parse!(argv) |
| 244 | return argv |
| 245 | rescue OptionParser::InvalidOption, OptionParser::MissingArgument |
| 246 | raise "Error: Invalid CLI option, #{opts.help.chomp}" |
| 247 | end |
| 248 | |
| 249 | # Method to clean the args. Windows cmd.exe treats single quotes as regular chars so we strip them if found. |
| 250 | def clean_argv(argv) |