OptionParser :: MissingArgument

时间:2017-01-09 18:08:14

标签: ruby rake

我想创建一个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 10.4.2
  • jruby 1.7.13

1 个答案:

答案 0 :(得分:1)

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

rake mytask -- -l

其中--表示“主要参数结束”,其余部分用于您的任务。

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

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

通过这种方式解决这个问题通常非常麻烦,而且用户不太友好,所以如果你能避免它并采用其他通常更好的方法。

相关问题