Writing usable scripts in Ruby


Usable command line tools/scripts

There are a lot of command line tools written in ruby, python, bash, c or any other languages. They are usable simply because there is a standard way in dealing with them
this way can be summarized in the following points:
  1. There has to be a usage example/brief help at the finger tips of the user ( by running with --help      or -h)
  2. arguments should have default values which are explained in the help
  3. misusage or missing mandatory arguments should fire the help message

ruby tools

OptionParser is part of the standard library in ruby that takes care of this script packaging.  they show long and short examples
This is an example of the script:
require 'optparse'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: script_name.rb [options]"
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
  options[:verbose] = v
end
end.parse!
p options
p ARGV
# Actual script code goes here
this allows the script to be used as:
$ ./script_name.rb -h
Usage: script_name.rb [options]
            -v, --[no-]verbose Run verbosely

$ ./script_name.rb -v
{:verbose=>true}
[]

$ ./script_name.rb
{}
[]

Packaging

no matter how small your script is, it is still better to package it as a gem. to keep track of releases, version, author.
let the actual code be part of the lib content. and the wrapper running (under bin) user OptParser and then call the script code with the specified options

Comments

Popular posts from this blog

Success of Startups

Prime Numbers Generator

Stress Testing with Siege and Bombard, know your limits