Ruby OptionParser empty switch "-" behavior

Go To StackoverFlow.com

0

EDITED:

I've wrote code that uses OptionParser to handle command line input gracefully. I am facing two major hits.

  1. Passing an empty switches '-' doesn't give an error. Of course some programs take that as valid, but mine shouldn't.
  2. The program requires two mandatory switches, but it accepts one switch without complaining! e.g. program.ruby -f foo -b bar is the valid input and both switches are :REQUIRED. But providing only one switch passes without problem and this is not the desired behavior.

For the first case I've done this:

opts.on('-', /\A-\Z/) do
  $stderr.print "Invalid empty switch"
  exit 1
end

It works fine. But is this the proper way of doing it?

For the second case, I've looked around for a solution within the OptionParser.new block but I couldn't find one. e.g.

unless options.foo && options.bar
  puts "Error."
  exit 2
end

Doing it outside the OptionParser.new block is the normal way?

2012-04-05 23:51
by ismail
Alright, I'll do the correction here, as I am trying to solve this meanwhile. For the empty switch to work properly I've used opts.on('-', /\A-\Z/) which does the trick of entering the block only after the regexp is met - ismail 2012-04-06 00:27
It is, I am not sure how did that happen, since I've actually performing edits as I explored the problem and kept refining the solution. How to get a moderator to redirect/delete this - ismail 2012-04-06 05:32
Since the other one has no answers, you may wish to just delete that one. Alternatively click the "flag" link below the question (and above these comments) and proceed accordingly - Andrew Marshall 2012-04-06 06:02


1

If you are using OptionParser, then yes, you need to explicitly disallow the empty switch and manually check the required parameters.

However, if you used another tool for option parsing, such as defunkt's gem choice, you could mark options as required and the invalid options (such as the empty switch) would cause the help to be printed and application to exit. I understand that in some cases it makes more sense to use OptionParser, but personally I prefer to use the more convenient tools out there.

Even though making options required is pretty easy one way or the other, I would recommend that you think your API decision through. How many command line utilities do you know, that have required options? There's a reason why command line is usually separated into options and arguments, with the former being usually optional and the latter usually required. I would stick to that established convention.

2012-04-06 11:23
by psyho


0

I think Thor(https://github.com/wycats/thor) can resolve your problem more efficiently.

2012-04-06 04:29
by LeoShi
+1 for thor -- it's very well built - joelparkerhenderson 2012-04-06 05:55
If by very well built you mean slow then sure, it's very well built - Jordon Bedwell 2015-05-11 20:57
Ads