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

swa*_*pab 1 ruby rake ruby-on-rails rake-task ruby-on-rails-3.2

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

一旦我发起父母耙

rake myapp:main
Run Code Online (Sandbox Code Playgroud)

然后在rake中调用done会为每个任务加载环境,还是在运行时只执行一次活动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
Run Code Online (Sandbox Code Playgroud)

Ami*_*ait 5

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

=> :environment被指定的:environment任务(由轨道限定)是你的任务的依赖,你的任务之前,必须调用.

您可以: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
Run Code Online (Sandbox Code Playgroud)

Rake维护一个intance变量@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
Run Code Online (Sandbox Code Playgroud)