Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby OptionParser::MissingArgument_Ruby_Rake - Fatal编程技术网

Ruby OptionParser::MissingArgument

Ruby OptionParser::MissingArgument,ruby,rake,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

我想创建一个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

如果您确实采用这种方法,则需要将任务的参数与
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
其中,
--
表示“主参数结束”,其余参数用于您的任务

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

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

这样做通常会非常混乱,而且不太方便用户,因此如果您可以避免这种情况,并使用其他通常更好的方法。

我不确定OptionParser是否是这里的最佳方案
rake
已经有了自己的解析选项,并且有了一种方法,可以用
VAR=value
传递数据,就像这里的
LOCAL=1
一样。例如,请参阅。@tadman我想让我的选项作为flagRake忽略我的参数,这就是它在历史上的工作方式,但你是对的,这在较新版本的
rake
中似乎不起作用。我在这里添加了一个版本,专门关注这些自定义参数。