Monday, April 12, 2010

Ruby OptionParser Library

I've spent way too much time dealing with a challenging situation while using Ruby's OptionParser class and I wanted to give the solution that I found because maybe one day someone else who is beating their head against a desk will stumble on this.
I created a -u, --username switch for the CLI:

Code Snippet:

opts.on("-u", "--username", "Enter your e-mail username") do |u|       options[:username] = u

and called it (for purposes of testing) by

options = OptparseExample.parse(ARGV)

puts options[:username]

Now the problem is I wouldn't receive the actual string value that followed the -u or --username switch back.

So -u cktricky came back either nil or true........not much of a help.

After hours of confusion, literally hours, and although I feel pretty ignorant right about now I am going to tell you what the problem was..........(highlighted the change)

opts.on("-u", "--username USERNAME", "Enter your e-mail username") do |u|       options[:username] = u

So, the only change here was that I added USERNAME (could be any string you wanted)........basically I thought the "on" method chose the parameters via comma separation like any normal parameter iteration. Turns out I was wrong. Total and utter weirdness.

With that I am going to go bandage my head :-)


mccroryme said...

This saved me after about 3 hours of Googling and fighting. Thank you for posting it!

cktricky said...

No problem, glad somebody else got some use from this. That nuance can be frustrating. Thank you for the feedback!