Tuesday, 11 May 2010 10:32
The optparse-simple gem uses a Polyrex document to fetch, and validate command-line arguments into a simple hash.
*installation*
sudo gem1.9.1 install optparse-simple
Successfully installed optparse-simple-0.2.0
1 gem installed
Installing ri documentation for optparse-simple-0.2.0...
Updating class cache with 3148 classes...
Installing RDoc documentation for optparse-simple-0.2.0...
Polyrex schema: options/option[name,switch,alias,value,mandatory]/error[msg]
*example*
require 'optparse-simple'
args = %w(-s --list=45 refresh filename filexx3)
h = OptParseSimple.new('/home/james/learning/ruby/optionsx.xml', args).to_h
#=> {:list=>"45", :sort=>nil, :refresh=>nil, :file1=>"filename", :file2=>"filexx3"}
file: optionsx.xml
list -l --list \d+ true
You must enter the list switch -l
incorrect value: please supply a valid list integer value e.g. -l=45
sort -s --sort false
invalid sort flag
print -p --print false
copy -c --copy false
refresh refresh true
you must include the refresh switch
file1 true
invalid sort flag
file2 true
invalid sort flag
Note: The error messages within each option are positioned by priority (mandatory being 1st, followed by value).
Resources:
- jrobertson's optparse-simple at master [github.com]
- Using OptParseSimple [dzone.com]
*update: 11-May-2010 @ 5:23pm*
To catch errors use the RuntimeError case e.g.
require 'optparse-simple'
begin
args = %w(-s --list=45 refresh filename filexx3 dhgf)
h = OptParseSimple.new('/home/james/learning/ruby/optionsx.xml', args).to_h
rescue RuntimeError => myStandardError
puts myStandardError
end
#=> invalid option: dhgf not recognised
see Handle exceptions in Ruby [dzone.com]Read more: