How to make Command Line Parameters Required in Ruby
I want to go over an easy to have a program stop processing if a required parameter is not passed in through the command line arguments.
I will show you how to do this with a piece of sample Ruby code that is not even twelve lines long.
By the end of the article, you will understand how to use OptionParser to parse parameters and when to quit the program when requiements are not met.
All of this will take less than two minutes of your time.
Shall we get started?
Introduction
I was working with OptionParser and wanted to have the program quit if the necessary arguments are not passed in by the user.
Library Feature?
Initially, I thought this was a feature of OptionParser, it’s in the documentation. After playing with it more, that feature just means the argument must have a value passed to it, not quitting when a required argument is not set at all.
Division of Labor
Ultimately, checking for required program arguments is not OptionParser’s job. It’s job is to parse arguments. Checking whether to quit the program because of missing arguments is upto another part of the program.
A Solution
A sample program demonstrating option parsing and exiting when a
required parameter is missing, in this case: -v
.
1
2
3
4
5
6
7
8
9
10
11
options = {}
OptionParser.new do |parser|
parser.on('-v', '--value VALUE', 'value to capture')
end.parse!(into: options)
unless options.keys.include?(:value)
puts 'missing key: --value'
exit
end
puts 'continuing'
Lines 6 - 9 contain the magic:
unless options.keys.include?(:value)
puts 'missing key: --value'
exit
end
After figuring this out, I realize: let OptionParser do it’s job of parsing arguments and have another piece of code check whether to proceed or not. Don’t conflate the two!
Trying it out
Let’s take this for a spin:
When passing in the required parameter, -v
, things are smooth:
vagrant@ubuntu-xenial:~$ ruby opts.rb -v value
options = {:value=>"value"}
continuing
When the -v
value is missing, the program displays a message and
processing stops:
vagrant@ubuntu-xenial:~$ ruby opts.rb -o
options = {:optional=>nil}
missing key: --value
Conclusion
Initially, it annoyed me that OptionParser would not cease program operation when a required argument was not passed in. After discovering a solution and thinking about this further, OptionParser is better to just parse arguments and let users of the library when to cease program execution instead of OptionParser.