Ruby optparse Limitations

[亡魂溺海] 提交于 2019-12-07 01:16:49

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/15487628/ruby-optparse-limitations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!