Search code examples
rubyrake

OptionParser::MissingArgument


I want to create a rake task that takes one parameter with no argument.

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

But it throws:

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

Meanwhile:

$ rake mytask -l random_arg
ready

Why?


  • Rake 10.4.2
  • jruby 1.7.13

Solution

  • If you do commit to this approach you need to separate your task's arguments from rake's own arguments:

    rake mytask -- -l
    

    Where -- means "end of main arguments" and the rest are for your task.

    You'll need to adjust your argument parsing to trigger only on those particular 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
    

    Going about it this way is usually really messy and not very user friendly, so if you can avoid it and employ some other method that's usually better.