2010-09-14 97 views
2

目录或文件,我发现我自己这样做往往:如何处理使用OptionParser

optparse = OptionParser.new do |opts| 
    options[:directory] = "/tmp/" 
    opts.on('-d','--dir DIR', String, 'Directory to put the output in.') do |x| 
    raise "No such directory" unless File.directory?(x) 
    options[:directory] = x 
    end 
end 

这将是更好,如果我可以指定DirPathname代替String。有没有一种模式或我的Ruby风格的方式来做到这一点?

回答

5

您可以配置OptionParser接受(例如)一个路径

require 'optparse' 
require 'pathname' 

OptionParser.accept(Pathname) do |pn| 
    begin 
    Pathname.new(pn) if pn 
    # code to verify existence 
    rescue ArgumentError 
    raise OptionParser::InvalidArgument, s 
    end 
end 

然后你就可以更改您的代码

opts.on('-d','--dir DIR',Pathname, 'Directory to put the output in.') do |x| 
+0

谢谢!这不仅回答了我的问题,而且给出了如何扩展optparse接受更多事情的一个很好的例子! – 2010-09-18 00:54:11

0

如果您正在寻找Ruby风格的做法,我会建议您尝试Trollop

从版本1.1o开始,您可以使用接受文件名,URI或字符串stdin-:io类型。

require 'trollop' 
opts = Trollop::options do 
    opt :source, "Source file (or URI) to print", 
     :type => :io, 
     :required => true 
end 
opts[:source].each { |l| puts "> #{l.chomp}" } 

如果您需要路径名,那么它不是你正在寻找的。但是如果你正在阅读文件,那么它是一个抽象它的强大方法。

+0

我不知道trollop。整齐!我一直在寻找optparse的具体答案,但我会在未来看看。 :-) – 2010-09-18 00:55:17