Search code examples
rubyoptparse

How to handle directories or files using OptionParser


I find my self doing this often:

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

It would be nicer if I could specify Dir or Pathname instead of String. Is there a pattern or my Ruby-esque way of doing this?


Solution

  • You can configure OptionParser to accept (for instance) a Pathname

    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
    

    Then you can change your code to

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