6

I need help using getoptlong class in Ruby. I need to execute command prog_name.ruby -u -i -s filename. So far I can only execute it with prog_name.ruby -u filename -i filename -s filename.

This is my getoptlong code:

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
4

2 回答 2

10

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

如果您gem install slop使用的是 RVM,则可以使用,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]nil,则不会再有任何争论,所以ARGV.empty?可能就足够了。
于 2011-04-16T21:01:41.087 回答
0

您在示例程序中有几个错误

  1. #each 和 #get 只返回选项中的第一个字符串,并将其他字符串转换为它。
  2. 您应该在选项处理之前检查参数
  3. 您可能不希望在您的日志记录类中使用它
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
于 2018-07-17T05:07:55.800 回答