从父rake调用多个任务是否为每个任务加载环境

如果我有一个耙子调用多个其他耙子。

一旦我发起父母耙

rake myapp:main 

然后在rake中调用完成将为每个任务加载环境,或者在运行rake myapp:main时只执行一次活动?

 namespace :myapp do desc "Main Run" task :main => :environment do Rake::Task['myapp:task1'].invoke Rake::Task['myapp:task2'].invoke end task :task1 => :environment do # Does the first task end task :task2 => :environment do # Does the second task end end 

将细节添加到@ Shadwell的答案..

=> :environment指定:environment任务(由rails定义)是您的任务的依赖项,必须在任务之前调用。

您可以在此处查看:environment任务的定义

https://github.com/rails/rails/blob/d70ba48c4dd6b57d8f38612ea95a3842337c1419/railties/lib/rails/application.rb#L428-432

Rake会跟踪已调用的任务,当它到达已经调用的依赖项时,它知道它可以跳过它。

https://github.com/jimweirich/rake/blob/5e59bccecaf480d1de565ab34fd15e54ff667660/lib/rake/task.rb#L195-204

 # Invoke all the prerequisites of a task. def invoke_prerequisites(task_args, invocation_chain) # :nodoc: if application.options.always_multitask invoke_prerequisites_concurrently(task_args, invocation_chain) else prerequisite_tasks.each { |p| prereq_args = task_args.new_scope(p.arg_names) p.invoke_with_call_chain(prereq_args, invocation_chain) } end end 

Rake维护一个@already_invoked变量@already_invoked来知道是否已经调用了一个任务。 在以下方法中可以看到相同的情况

https://github.com/jimweirich/rake/blob/5e59bccecaf480d1de565ab34fd15e54ff667660/lib/rake/task.rb#L170-184

 def invoke_with_call_chain(task_args, invocation_chain) # :nodoc: new_chain = InvocationChain.append(self, invocation_chain) @lock.synchronize do if application.options.trace application.trace "** Invoke #{name} #{format_trace_flags}" end return if @already_invoked @already_invoked = true invoke_prerequisites(task_args, new_chain) execute(task_args) if needed? end rescue Exception => ex add_chain_to(ex, new_chain) raise ex end 

环境只会设置一次。

=> :environment指定:environment任务(由rails定义)是您的任务的依赖项,必须在任务之前调用。 Rake会跟踪已调用的任务,当它到达已经调用的依赖项时,它知道它可以跳过它。

(旁白:如果你真的希望多次调用依赖项,这可能会导致问题)

您还可以使用依赖项定义main任务:

 task :main => [:task1, :task2] do # Blank end 

当您运行rake myapp:main ,它将查看依赖项并调用task1 ,然后调用task2 。 因为task1具有依赖environment所以它也将首先调用它。 但它会跳过对task2environment依赖。

答案为否,从父任务执行另一个Rake任务时未加载环境。 对此的简单解释是以下代码:

 namespace :myapp do desc "Main Run" task :main => :environment do puts "Start Time : #{Time.now.to_i}" Rake::Task['myapp:task1'].invoke puts "End Time1 : #{Time.now.to_i}" Rake::Task['myapp:task2'].invoke puts "End Time2 : #{Time.now.to_i}" end task :task1 => :environment do # Does the first task puts "Executing..1" end task :task2 => :environment do # Does the second task puts "Executing..2" end end 

但是,执行两个或多个rake任务并不是一个好习惯。 如果你想实现同样的东西,你可以模块化代码,并创建两个函数并调用函数来实现相同的结果。