如何使用 OptionParser 解析 rake 参数

How to parse rake arguments with OptionParser

Reffering that answer 我正在尝试使用 OptionParser 来解析 rake 参数。我从那里简化了示例,我必须添加两个 ARGV.shift 才能使其工作。

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

这是输出:

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

我认为 ARGV.shift 不是应该的方式。我想知道为什么没有它它就不能工作,以及如何以正确的方式修复它。

你必须在 -ufoo 之间加上一个 '=':

$ rake user:create -- -u=foo

而不是:

$ rake user:create -- -u foo

我知道这并不能严格回答您的问题,但您是否考虑过使用任务参数?

这将使您不必 fiddle 与 OptionParserARGV:

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

有关详细信息,请参阅 this answer here on SO

您可以使用方法 OptionParser#order! which returns ARGV 而没有错误的参数:

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]}"

您可以像这样传递参数:$ rake foo:bar -- '--user=john'

试试这个:

require 'optparse'

namespace :programs do |args|
  desc "Download whatever"
  task :download => [:environment] do

    # USAGE: rake programs:download -- rm
    #-- Setting options $ rake programs:download -- --rm
    options = {}
    option_parser = OptionParser.new
    option_parser.banner = "Usage: rake programs:download -- rm"
    option_parser.on("-r", "--rm","Remove s3 files downloaded") do |value|
      options[:remove] = value
    end
    args = option_parser.order!(ARGV) {}
    option_parser.parse!(args)
    #-- end

    # your code here
  end
end