On Wed, 10 Nov 2004 nobu.nokada / softhome.net wrote:

thanks nobu!  i've been dying to know how to do this!

-a

> #! /usr/bin/ruby
> require 'optparse'
> require 'pp'
>
> @host = @port = nil
>
> # general options
> opt = OptionParser.new do |opt|
>  opt.banner = "Usage: #{$0} [general options] subcommand [specific options]"
>  opt.define("  general options:")
>  opt.define('--host HOST', String) {|host| @host = host}
>  opt.define('--port PORT', Integer) {|port| @port = port}
> end
>
> # specific option initializers
> specific = {
>  "login" => proc do |opt|
>    @passwd = nil
>    opt.define("--password PASSWORD", String) {|passwd| @passwd = passwd}
>  end,
>  "list" => proc do |opt|
>    @open = false
>    opt.define("--open") {|open| @open = true}
>  end,
> }
> missing = proc {|opt|
>  opt.define(["  subcommand:", specific.keys.sort].join("\n\t"))
> }
>
> begin
>  cmd = nil
>  opt.order!(ARGV) {|cmd| opt.terminate}
>  opt = OptionParser.new(opt) do |opt|
>    unless cmd
>      abort "#{$0}: command missing\n#{missing[opt]}"
>    end
>    subopt = specific.fetch(cmd) do
>      abort "#{$0}: unknown command: #{cmd}\n#{missing[opt]}"
>    end
>    opt.define("  specific options for #{cmd}:")
>    subopt[opt]
>  end
>  opt.parse!(ARGV)
> rescue OptionParser::ParseError => e
>  abort "#{e}\n#{opt}"
> end
> pp self
>
>
> --
> Nobu Nakada
>
>
>

-a
--
===============================================================================
| EMAIL   :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
| PHONE   :: 303.497.6469
| When you do something, you should burn yourself completely, like a good
| bonfire, leaving no trace of yourself.  --Shunryu Suzuki
===============================================================================