Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse rake arguments with OptionParser

Reffering that answer I was trying to use OptionParser to parse rake arguments. I simplified example from there and I had to add two ARGV.shift to make it work.

require 'optparse'

namespace :user do |args|

  # Fix I hate to have here
  puts "ARGV: #{ARGV}"
  ARGV.shift
  ARGV.shift
  puts "ARGV: #{ARGV}"

  desc 'Creates user account with given credentials: rake user:create'
  # environment is required to have access to Rails models
  task :create => :environment do
    options = {}
    OptionParser.new(args) do |opts|      
      opts.banner = "Usage: rake user:create [options]"
      opts.on("-u", "--user {username}","Username") { |user| options[:user] = user }
    end.parse!

    puts "user: #{options[:user]}"

    exit 0
  end
end

This is the output:

$ rake user:create -- -u foo
ARGV: ["user:create", "--", "-u", "foo"]
ARGV: ["-u", "foo"]
user: foo

I assume ARGV.shift is not the way it should be done. I would like to know why it doesn't work without it and how to fix it in a proper way.

like image 208
pawel7318 Avatar asked Jan 23 '15 12:01

pawel7318


2 Answers

You can use the method OptionParser#order! which returns ARGV without the wrong arguments:

options = {}

o = OptionParser.new

o.banner = "Usage: rake user:create [options]"
o.on("-u NAME", "--user NAME") { |username|
  options[:user] = username
}
args = o.order!(ARGV) {}
o.parse!(args)
puts "user: #{options[:user]}"

You can pass args like that: $ rake foo:bar -- '--user=john'

like image 110
3 revsRoger Pate Avatar answered Sep 19 '22 15:09

3 revsRoger Pate


I know this does not strictly answer your question, but did you consider using task arguments?

That would free you having to fiddle with OptionParser and ARGV:

namespace :user do |args|
  desc 'Creates user account with given credentials: rake user:create'
  task :create, [:username] => :environment do |t, args|
    # when called with rake user:create[foo],
    # args is now {username: 'foo'} and you can access it with args[:username]
  end
end

For more info, see this answer here on SO.

like image 24
awendt Avatar answered Sep 18 '22 15:09

awendt