0

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
Viktor
  • 4,218
  • 4
  • 32
  • 63
  • I'm not sure OptionParser is the best plan here. `rake` already has its own option parsing and a method for passing in data with `VAR=value` at the end, like here `LOCAL=1` would work. See [this answer](http://stackoverflow.com/questions/825748/how-to-pass-command-line-arguments-to-a-rake-task) for examples. – tadman Jan 09 '17 at 18:13
  • @tadman I want to have my option as flag – Viktor Jan 09 '17 at 18:14

1 Answers1

1

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.

tadman
  • 208,517
  • 23
  • 234
  • 262