关于ruby on rails:如何使用OptionParser解析rake参数

How to parse rake arguments with OptionParser

参考这个答案,我试图用OptionParser来分析rake的论点。我从那里简化了示例,我必须添加两个ARGV.shift才能使其工作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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

这是输出:

1
2
3
4
$ rake user:create -- -u foo
ARGV: ["user:create","--","-u","foo"]
ARGV: ["-u","foo"]
user: foo

我想江户一〔二〕不是应该这样做的。我想知道没有它为什么不起作用,以及如何以正确的方式修复它。


您可以使用方法OptionParser#order!返回argv而不使用错误的参数:

1
2
3
4
5
6
7
8
9
10
11
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'


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

这样你就可以随意摆弄OptionParserARGV

1
2
3
4
5
6
7
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

有关更多信息,请参见下面的答案。


1
<script src="https://gist.github.com/altherlex/bb67f17cb8eefb281866fc21dfeb921a.js">

一个澄清的例子:

其他提示要点

https://gist.github.com/altherlex/bb67f17cb8eefb281866fc21dfeb921a


必须在-ufoo之间加"=":

$ rake user:create -- -u=foo

而不是:

$ rake user:create -- -u foo