DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Optparse (script) Template

08.31.2005
| 10394 views |
  • submit to reddit
        
require 'optparse'

# default options
OPTIONS = {
  :first       => "default value",
  :another     => 23,
  :bool        => false,
  :list        => ["x", "y", "z"],
  :dest        => File.expand_path(File.dirname($0))
}


ARGV.options do |o|
  script_name = File.basename($0)
  
  o.set_summary_indent('  ')
  o.banner =    "Usage: #{script_name} [OPTIONS]"
  o.define_head "Abstract description of script"
  o.separator   ""
  o.separator   "Mandatory arguments to long options are mandatory for " +
                "short options too."
  
  o.on("-f", "--first=[val]", String,
       "A long and short (optional) string argument",
       "Default: #{OPTIONS[:first]}")   { |OPTIONS[:first]| }
  o.on("-a", "--another=val", Integer,
       "Requires an int argument")      { |OPTIONS[:another]| }
  o.on("-b", "--boolean",
       "A boolean argument")            { |OPTIONS[:bool]| }
  o.on("--list=[x,y,z]", Array, 
       "Example 'list' of arguments")   { |OPTIONS[:list]| }
  
  o.separator ""

  o.on_tail("-h", "--help", "Show this help message.") { puts o; exit }
  
  o.parse!
end

puts "first:     #{OPTIONS[:first]}"
puts "another:   #{OPTIONS[:another]}"
puts "bool:      #{OPTIONS[:bool]}"
puts "list:      #{OPTIONS[:list].join(',')}"
puts "arguments: #{ARGV}"