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}"
end

if __FILE__ == $PROGRAM_NAME
  if ARGV[0]
    main(ARGV[0])
  else
    puts "usage: ruby #{__FILE__} FILENAME"
  end
end

Now with CLAP I can add some real options.

require 'rubygems'
require 'clap'

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

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

if __FILE__ == $PROGRAM_NAME
  # set defaults
  verbose = false
  filename = nil

  # parse the command line
  Clap.run 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?
end
About these ads
Tagged with: ,
Posted in ruby

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.

Join 34 other followers

%d bloggers like this: