I currently script in Python but I wish to try Ruby for several reasons. I've looked at a lot of sample code and read a lot of documentation over the last week. One point of concern I have is the lack of a proper command line argument parsing libraries in Ruby. Ruby experts, don't get mad at me — maybe I don't know. That's why I am here.
In Python, I was used to using argparse
which in my opinion is simply perfect (maybe for my needs). Unfortunately though, OptionParser
doesn't allow for the flexibility and features that argparse
does.
I am specifically looking at the following constraints for now:
How do I make mutually exclusive option lists? For e.g. a very small option list for a program called test
.
usage: test [-h] [-a | -b | -c] [-d] [filename]
I can write some code like:
# implement a ----------------------------------------------
opts.on( "-a", "--alpha",
"implement alpha") do
#...
end
and so on. But then, I've no way to make a
, b
and c
mutually exclusive unless I code a permutation of those and do some error handling. For e.g.
test -ab #should through an error
In Python, I could do this in a very easy way:
# create an command line argument parser object
cmd_line_parser = argparse.ArgumentParser()
# create a mutually exclusive group
cmd_line_group = cmd_line_parser.add_mutually_exclusive_group()
Secondly, I've no way of pairing -d
with -a
unless I specifically write code for this permutation. This is insane.
I've to write the [OPTION]
list myself; I've no way to know if I am wrong or right unless and until I do a blackbox testing for all possible input permutations and map them to the blackbox list.
Moreover, compulsory arguments again need to be handled using special code.
Is there an easy of handling these constraints using optparse
or other libraries in Ruby?
There is docopt library that has both Python and Ruby implementations. The specification for the test
program is:
usage: test [-h] [-a | -b | -c] [-d] [<filename>]
a,b,c options are mutually exclusive (-ab
produces an error), it supports combined options: -ad
, -da
, etc.
To make the filename
parameter mandatory:
usage: test [-h] [-a | -b | -c] [-d] <filename>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With