Ruby optparse Limitations
Asked Answered
H

1

8

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:

  1. 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()
    
    1. Secondly, I've no way of pairing -d with -a unless I specifically write code for this permutation. This is insane.

    2. 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.

    3. 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?

Heidt answered 18/3, 2013 at 21:51 Comment(0)
C
11

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>
Catacaustic answered 18/3, 2013 at 22:34 Comment(1)
Wow. That is insane. Epic. Period. What the hell have I been doing for so long. That is awesome. Thanks a lot.Heidt

© 2022 - 2024 — McMap. All rights reserved.