CLAP – Command Line Arguments Parsing

I’m not sure how many gems/libraries there are in Ruby to parse command line arguments, but today I discovered a new one: CLAP.

Most of the time when I’m writing a script, all I need to do is get one or two arguments from the command line and maybe print a usage message. To be honest I never mastered the OptionParser class, it just seems like overkill when writing a small script.

So most of the time I cheat and do something like this:

def main(filename)
  puts "filename = #{filename}"

  if ARGV[0]
    puts "usage: ruby #{__FILE__} FILENAME"

Now with CLAP I can add some real options.

require 'rubygems'
require 'clap'

def usage
  puts "usage: ruby #{__FILE__} --file FILENAME"

def main(filename, verbose=false)
  puts "filename = #{filename}"
  puts "verbose = #{verbose}"

  # set defaults
  verbose = false
  filename = nil

  # parse the command line ARGV,
    "-v" => lambda { verbose = true },
    "-f" => lambda { |arg| filename = arg },
    "--file" => lambda { |arg| filename = arg }
  # execute
  main(filename, verbose) unless filename.nil?
  usage if filename.nil?
Tagged with: ,
Posted in ruby

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: