How to parse rake arguments with OptionParser
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'
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.