proposal: map method for getoptlong

From: Wybo Dekker <wybo@...>
Date: 2004-05-21 22:07:01 UTC
List: ruby-core #2917
usually, when using getoptlong, one wants to test if an option was set,
and (if it requires an argument) to which value. To make that test easier,
I propose that getoptlong be extended with a map method. The following
script makes that extension and then tests it; try it first with the -h
option:

#!/usr/bin/ruby

require 'getoptlong';

class GetoptLong

   # map getoptlong options to global variables named after their
   # (optionally prefixed) main name. 
   # Usage example:: link:../getoptlong_example

   def map(*prefix)
      loop do
        option_name, option_argument = get_option
        break if option_name == nil
        eval "$#{prefix||''}#{option_name.tr('-','')} = " + 
             "#{option_argument=='' ? 'true' : 'option_argument'}"
      end
   end
end

opt = GetoptLong.new(
   [ '--help',   '-h', GetoptLong::NO_ARGUMENT ],
   [ '--short',  '-s', GetoptLong::OPTIONAL_ARGUMENT ],
   [ '--offset', '-o', GetoptLong::REQUIRED_ARGUMENT ]
).map('opt_')

if $opt_help 
   puts <<-EOF
   You can run #{$0.sub(/.*\//,'')} with the following options:
       --help   or -h (no argument) prints this help
       --short  or -s (no argument) prints option information
       --offset or -o (requires an argument) prints option information
   EOF
   exit
end

puts "$opt_short  was #{$opt_short ? 'set' : 'unset'}, "+
     "it's class is #{$opt_short.class} and "+
     ( $opt_short ? "it contains #{$opt_short}" : "is empty" )

puts "$opt_offset was #{$opt_offset ? 'set' : 'unset'}, "+
     "it's class is #{$opt_offset.class} and "+
     ( $opt_offset ? "it contains #{$opt_offset}" : "is empty" )


-- 
Wybo Dekker

In This Thread

Prev Next