Example with optparse

require 'optparse'
 
# Create our options structure
ProgramOptions = Struct.new( "ProgramOptions", :host, :port, :version, :appname, :verbose )
 
# Create a custom data type to show OptionParser's support for handling additional data types
VersionInfo = Struct.new( "VersionInfo", :major, :minor )
 
# set default values
options = ProgramOptions.new( "localhost", 8808, VersionInfo.new( 2, 0 ), "myapp", false )
 
# Setup the option parser
optparse = OptionParser.new
 
# lets add support specifically for our #.# VersionInfo objects
optparse.accept( VersionInfo, /(\d)\.(\d)/ ) { |v, major, minor| VersionInfo.new( major, minor ) }
 
# provide event handlers for each argument that is encountered.
optparse.on( "--host", "=HOST" )                     { |host| options.host = host }
optparse.on( "--port", "=PORT", Integer )            { |port| options.port = port }
optparse.on( "--version", "=VERSION", VersionInfo  ) { |version| options.version = version }
optparse.on( "--name", "=NAME" )                     { |appname| options.appname = appname }
optparse.on( "--verbose" )                           { options.verbose = true }
optparse.on( "--help" ) { # help
puts <<EOF
ruby opt.rb [options]
  --host h (default: #{options.host})
  --port p (default: #{options.port})
  --version m.n (default: #{options.version.major}.#{options.version.minor})
  --name n (default: #{options.appname})
  --verbose (default: #{options.verbose})
  --help => print this help
 
EOF
exit -1
}
 
begin
    # Now parse from the passed in arguments.
    optparse.parse( ARGV )
 
    # Show what happened...
    puts "Running with the following Options: "
    puts "HOST:    #{ options.host }"
    puts "PORT:    #{ options.port }"
    puts "VERSION: #{ options.version.major }.#{ options.version.minor }"
    puts "APPNAME: #{ options.appname }"
    puts "VERBOSE: #{ options.verbose }"
rescue => e
    puts e.message
end

Another example

# /home/mnain/learn/ruby/check_proc.rb
#
 
require 'optparse'
 
ProgramOptions = Struct.new("Options", :configFile, :pollPeriod)
optfile = ENV['HOME'] + "/check_proc.cfg"
 
options = ProgramOptions.new(optfile, 60)
procsToMonitor = Array.new
optparse = OptionParser.new
optparse.on("-c","--config [FILE]","Config") { |opt| options.configFile = opt }
optparse.on("-w","--wait [SECS]",Integer,"Wait") { |opt| options.pollPeriod = opt }
optparse.on("-p","--proc [proc1,proc2,proc3]",Array,"Process") { |opt|
    opt.each { |e|
        procsToMonitor.push e
    }
}
 
begin
optparse.parse(ARGV)
rescue
puts "Args processed"
end
 
p options
p procsToMonitor
 
results = `/usr/bin/pgrep myProcess`.chomp.to_i
p results
~

optparse.txt · Last modified: 2014/10/26 01:52 (external edit)
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0