如何在ruby中使用getoptlong类?

时间:2011-04-16 18:39:07

标签: ruby getopt-long

我在Ruby中使用getoptlong类需要帮助。我需要执行命令prog_name.ruby -u -i -s filename。到目前为止,我只能用prog_name.ruby -u filename -i filename -s filename。

执行它

这是我的getoptlong代码:

require 'getoptlong'

class CommonLog
parser = GetoptLong.new
parser.set_options(["-h", "--help", GetoptLong::NO_ARGUMENT],
                   ["-u", "--url",  GetoptLong::NO_ARGUMENT],
                   ["-i", "--ip",   GetoptLong::NO_ARGUMENT],
                   ["-s", "--stat", GetoptLong::NO_ARGUMENT])

begin
  begin
      opt,arg = parser.get_option
      break if not opt

      case opt
         when "-h" || "--help"
           puts "Usage: -u  filename"
           puts "Usage: -i  filename"
           puts "Usage: -s  filename"
         exit
         when "-u" || "--url"
            log = CommonLog.new(ARGV[0])
            log.urlReport
         when "-i" || "--ip"
            log = CommonLog.new(ARGV[0])
            log.ipReport
         when "-s" || "--stat"
            log = CommonLog.new(ARGV[0])
            log.statReport
         end
      rescue => err
         puts "#{err.class()}: #{err.message}"
         puts "Usage: -h -u -i -s filename"
      exit
   end
end while 1

if ARGV[0] == nil || ARGV.size != 1
   puts "invalid! option and filename required"
   puts "usage: -h -u -i -s filename"
end

2 个答案:

答案 0 :(得分:10)

我将通过推荐查看新的“slop”宝石来回答。它是getoptlong的包装器。

如果您使用的是RVM,则可以使用gem install slop,否则可以使用sudo gem install slop

GetOptLong功能非常强大但是,虽然我已多次使用它,但我仍然需要每次都查看文档。

如果你想要更强大的功能,使用“比GetOptLong更容易使用的界面”,请查看Ruby的OptionParser。您需要更好地计算逻辑,但这是转换代码的快速通道。我不得不为CommonLog gem创建一个类,因为我没有使用它。重要的事情是从ARGV

中拉出日志
require 'optparse'

class CommonLog
  def initialize(*args); end
  def urlReport();     puts "running urlReport()";        end
  def ipReport();      puts "running ipReport()";         end
  def statReport(arg); puts "running statReport(#{arg})"; end
end

log = CommonLog.new(ARGV[0])

OptionParser.new { |opts|
  opts.banner = "Usage: #{File.basename($0)} -u -i -s filename"

  opts.on( '-u', '--[no-]url', 'some short text describing URL') do
    log.urlReport()
  end

  opts.on('-i', '--[no-]ip', 'some short text describing IP') do
    log.ipReport()
  end

  opts.on('-s', '--stat FILENAME', 'some short text describing STAT') do |arg|
    log.statReport(arg)
  end
}.parse!

另外,作为一个快速的批评,你不是在编写惯用的Ruby代码:

  • when语句可以写成:when "-h", "--help"
  • if ARGV[0] == nil || ARGV.size != 1令人费解。研究ARGV和阵列的工作原理。通常,如果ARGV[0]为零,则不会有更多参数,因此ARGV.empty?可能就足够了。

答案 1 :(得分:0)

  

示例程序中有几个错误

     
      
  1. #each和#get仅返回选项中的第一个字符串,并将其他字符串转换为该字符串。
  2.   
  3. 您应该在选项处理之前将检查参数的位置放进去
  4.   
  5. 您可能不希望在日志记录类中使用它
  6.   
require 'getoptlong'
# don't pollute CommonLog with this
include CommonLog
# if this is the startup module
if __FILE__ == $0 then
  # Check to ensure there are arguments
  if ARGV.size < 1
    puts "invalid! option and filename required"
    puts "usage: -h -u -i -s filename"
  end
  # set up parser and get the options
  parser_opts=GetoptLong.new(
    ["--help", "-h", GetoptLong::NO_ARGUMENT],
    ["--url", "-u", GetoptLong::NO_ARGUMENT],
    ["--ip", "-i", "--ip", GetoptLong::NO_ARGUMENT],
    ["--stat", "-s", GetoptLong::NO_ARGUMENT]
  )

  parser_opts.each do |opt,arg|
    begin # this is for the exception processing
      case opt
      when "--help" #only the first option is returned read ruby doc on #each
        puts "Usage: -u  filename"
        puts "Usage: -i  filename"
        puts "Usage: -s  filename"
        exit
      when "--url" #only the first option is returned
        log = CommonLog.new(ARGV[0])
        log.urlReport
      when "--ip" #only the first option is returned
        log = CommonLog.new(ARGV[0])
        log.ipReport
      when "--stat" #only the first option is returned
        log = CommonLog.new(ARGV[0])
        log.statReport
      else # this should not be used
        puts "unexpected option %s"%opt 
        puts "Usage: -h -u -i -s filename"
      end
    rescue Exception => err #rescuing an unexpected Exception
      puts "#{err.class()}: #{err.message}"
      puts "Usage: -h -u -i -s filename"
      Kernel.exit
    end
  end
end