OptionParser::MissingArgument

OptionParser::MissingArgument

我想创建一个只接受一个参数而不带参数的 rake 任务。

task :mytask => :environment do
  options = Hash.new
  OptionParser.new do |opts|
    opts.on('-l', '--local', 'Run locally') do
      options[:local] = true
    end
  end.parse!

  # some code

end

但它抛出:

$ rake mytask -l
rake aborted!
OptionParser::MissingArgument: missing argument: -l

同时:

$ rake mytask -l random_arg
ready

为什么?


如果您确实采用这种方法,则需要将任务的参数与 rake 自己的参数分开:

rake mytask -- -l

其中 -- 表示 "end of main arguments",其余的是您的任务。

您需要调整参数解析以仅在这些特定参数上触发:

task :default do |t, args|
  # Extract all the rake-task specific arguments (after --)
  args = ARGV.slice_after('--').to_a.last

  options = { }
  OptionParser.new do |opts|
    opts.on('-l', '--local', 'Run locally') do
      options[:local] = true
    end
  end.parse!(args)

  # some code
end

以这种方式进行操作通常非常混乱并且对用户不太友好,因此如果您可以避免这种情况并采用通常更好的其他方法。