如何使用OptionParser处理目录或文件

时间:2010-09-14 20:13:45

标签: ruby optparse

我经常发现自己这样做:

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式方式来做到这一点?

2 个答案:

答案 0 :(得分: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|

答案 1 :(得分:0)

如果您正在寻找一种Ruby式的方式,我建议您尝试Trollop

从版本1.1o开始,您可以使用接受文件名,URI或字符串:iostdin的{​​{1}}类型。

-

如果您需要路径名,那么它不是您想要的。但是如果你想要阅读文件,那么它是一种强大的抽象方式。

相关问题