I originally intended these random ‘Simplicity’ updates to be about things I like in Ruby that are a pain to do in Java. And while that’s certainly the case this time around, this comes from a library perspective rather than the languge itself. Specifically, I’m talking about processing command-line arguments. It’s something you have to do all the time when you write these little scripts that come up but for some reason results in the same boilerplate code being constructed. This is why I’m exceptionally glad that Ruby has many solutions to this problem.
So, just to clarify, this is the problem. The user types in this:
./myprogram --file data.txt --optional-thing true --whatever 100
And I want to be able to make sure they put in certain flags, and that they meet some criteria, and get the data I need out of it. Coming from Java-land, I wasn’t taught anything in particular to do this, and Google really only reveals a useful how-to to write your own. Their solution seems to be the equivalent of writing an interpreter for your command line arguments, and is a bit over-the-top for something this simple.
Ruby, strangely enough, has at least half a dozen different competing libraries that specifically serve the purpose of parsing command-line arguments (two of which are built into the language). The one I chose was the first one that showed up on Google, OptiFlag. It bills itself as a Domain Specific Language for command-line arguments, which still sounds weird to me. However, their implementation is pretty solid. The way the JavaWorld article suggests seems pretty bulky, but with these guys, you download their package, include it in your program, and once you learn how to ‘speak’ their language, you can rip out everything you need in a line or two of code.
The documentation on OptiFlag is amazing too! The simple tutorial and clear pictures make it really easy to pick and grab whatever you need to do what you have to do, and the fact that arguments can be validated via regex is amazing. Not that anything is groundbreaking there, but the fact that you can saves more boilerplate code in the long run.
If you do a lot of little scripts that use the command line, check out OptiFlag, and if you use Ruby and haven’t seen OptiFlag, go check it out. It’s definitely a different take on command-line argument processing.