2

私はこれを頻繁にやっていることに気づきます:

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

orの代わりにDirorを指定できればもっといいのですが。これを行うパターンまたはRuby風の方法はありますか?PathnameString

4

2 に答える 2

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|
于 2010-09-14T21:38:04.913 に答える
0

それを行うための Ruby 風の方法を探している場合は、Trollopを試してみることをお勧めします。

バージョン 1.1o 以降:io、ファイル名、URI、または文字列stdinまたは-.

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}" }

パス名が必要な場合は、探しているものではありません。しかし、ファイルを読みたい場合は、それを抽象化する強力な方法です。

于 2010-09-14T20:48:56.390 に答える