如何将命名参数传递给 Rake 任务? [英] How can I pass named arguments to a Rake task?
问题描述
有没有办法在不使用环境变量的情况下将命名参数传递给 Rake 任务?
我知道 Rake 任务可以接受两种格式的参数:
环境变量
$ rake my_task foo=bar
这将创建一个名为 foo
和值 bar
的环境变量,可以在 Rake 任务 my_task
中通过 访问ENV['foo']
.
Rake 任务参数
$ rake my_task['foo','bar']
这会将值 foo
和 bar
传递给前两个任务参数(如果已定义).如果 my_task
被定义为:
task :my_task, :argument_1, :argument_2
然后 argument_1
的值为 foo
,argument_2
的值为 bar
.
你可以这样说:
rake some_task -- --arg=value
然后,在您的任务中,ARGV
将是
[ 'some_task', '--arg=value' ]
所以你可以使用 OptionParser (或其他一些选项解析器)来解压 ARGV
就像在任何旧的 CLI 脚本中一样;看起来很有趣的 --
是必要的,以防止 rake 试图将 --arg=like
解析为 rake 开关.
使用标准环境变量方法可能会更好,它不像所有 --
东西那么丑陋,而且它是将参数传递给 rake 任务的常用方法.>
Is there a way to pass named arguments to a Rake task without using environment variables?
I am aware that Rake tasks can accept arguments in two formats:
Environment Variables
$ rake my_task foo=bar
This creates an environment variable with the name foo
and the value bar
that can be accessed in the Rake task my_task
by ENV['foo']
.
Rake Task Arguments
$ rake my_task['foo','bar']
This passes the values foo
and bar
to the first two task arguments (if they are defined). If my_task
were defined as:
task :my_task, :argument_1, :argument_2
then argument_1
would have the value foo
and argument_2
would have the value bar
.
You can say things like this:
rake some_task -- --arg=value
And then, inside your task, ARGV
will be
[ 'some_task', '--arg=value' ]
so you could use OptionParser (or some other option parser) to unpack ARGV
just like in any old CLI script; the funny looking --
is necessary to keep rake from trying to parse --arg=like
as a rake switch.
You're probably better off with the standard environment variable approach, it isn't as ugly as all the --
stuff and it is the usual way of passing arguments to rake tasks.
这篇关于如何将命名参数传递给 Rake 任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!