-
慕姐8265434
选项和依赖项必须在数组中:namespace :thing do
desc "it does a thing"
task :work, [:option, :foo, :bar] do |task, args|
puts "work", args end
task :another, [:option, :foo, :bar] do |task, args|
puts "another #{args}"
Rake::Task["thing:work"].invoke(args[:option], args[:foo], args[:bar])
# or splat the args
# Rake::Task["thing:work"].invoke(*args)
endend然后rake thing:work[1,2,3]=> work: {:option=>"1", :foo=>"2", :bar=>"3"}rake thing:another[1,2,3]=> another {:option=>"1",
:foo=>"2", :bar=>"3"}=> work: {:option=>"1", :foo=>"2", :bar=>"3"}注:可变task是任务对象,除非您了解/关心Rake内部组件,否则不会很有帮助。Rails注:如果从Rails运行任务,最好通过添加=> [:environment]这是一种设置相依任务。 task :work, [:option, :foo, :bar] => [:environment] do |task, args|
puts "work", args end
-
心有法竹
通过向任务调用添加符号参数,可以在rake中指定形式参数。例如:require 'rake'task :my_task, [:arg1, :arg2] do |t, args|
puts "Args were: #{args}"endtask :invoke_my_task do
Rake.application.invoke_task("my_task[1, 2]")end# or if you prefer this syntax...task :invoke_my_task_2 do
Rake::Task[:my_task].invoke(3, 4)end# a task with prerequisites passes its # arguments to it prerequisitestask :with_prerequisite,
[:arg1, :arg2] => :my_task #<- name of prerequisite task# to specify default values, # we take advantage of args being a Rake::
TaskArguments objecttask :with_defaults, :arg1, :arg2 do |t, args|
args.with_defaults(:arg1 => :default_1, :arg2 => :default_2)
puts "Args with defaults were: #{args}"end然后,从命令行:> rake my_task[1,2]
Args were: {:arg1=>"1", :arg2=>"2"}
> rake "my_task[1, 2]"
Args were: {:arg1=>"1", :arg2=>"2"}
> rake invoke_my_task
Args were: {:arg1=>"1", :arg2=>"2"}
> rake invoke_my_task_2
Args were: {:arg1=>3, :arg2=>4}
> rake with_prerequisite[5,6]
Args were: {:arg1=>"5", :arg2=>"6"}
> rake with_defaults
Args with defaults were: {:arg1=>:default_1, :arg2=>:default_2}
> rake with_defaults['x','y']
Args with defaults were: {:arg1=>"x", :arg2=>"y"}如第二个示例所示,如果要使用空格,目标名称周围的引号是必要的,以防止shell在空间中分割参数。查看rake.rb,看起来rake不解析任务字符串来提取先决条件的参数,所以您不能这样做。task :t1 => "dep[1,2]"..为先决条件指定不同参数的唯一方法是在依赖任务操作中显式调用它,如:invoke_my_task和:invoke_my_task_2.请注意,有些shell(如zsh)要求您转义括号:rake my_task\['arg1'\]
-
喵喵时光机
除了kch的回答(我没有找到如何留下评论,对不起):您不必将变量指定为ENV变量之前的变量。rake命令。您可以像通常那样设置命令行参数:rake mytask var=foo并以ENV变量的形式访问rake文件中的这些变量,如下所示:p ENV['var'] # => "foo"