2010-04-04 50 views
13

我在寫一個Rake腳本,它包含帶參數的任務。我想出瞭如何傳遞參數以及如何使任務依賴於其他任務。如何將父任務的參數傳遞給Rake中的子任務?

task :parent, [:parent_argument1, :parent_argument2, :parent_argument3] => [:child1, :child2] do 
    # Perform Parent Task Functionalities 
end 

task :child1, [:child1_argument1, :child1_argument2] do |t, args| 
    # Perform Child1 Task Functionalities 
end 

task :child2, [:child2_argument1, :child2_argument2] do |t, args| 
    # Perform Child2 Task Functionalities 
end 
  • 我可以傳遞參數從父任務的子任務?
  • 有沒有辦法讓孩子的任務爲私人,所以他們不能獨立調用?

回答

26

我實際上可以想到在Rake任務之間傳遞參數的三種方法。

  1. 使用rake的內置的論據支持:

    # accepts argument :one and depends on the :second task. 
    task :first, [:one] => :second do |t, args| 
        puts args.inspect # => '{ :one => "one" }' 
    end 
    
    # argument :one was automagically passed from task :first. 
    task :second, :one do |t, args| 
        puts args.inspect # => '{ :one => "one" }' 
    end 
    
    $ rake first[one] 
    
  2. 通過Rake::Task#invoke直接調用任務:

    # accepts arguments :one, :two and passes them to the :second task. 
    task :first, :one, :two do |t, args| 
        puts args.inspect # => '{ :one => "1", :two => "2" }' 
        task(:second).invoke(args[:one], args[:two]) 
    end 
    
    # accepts arguments :third, :fourth which got passed via #invoke. 
    # notice that arguments are passed by position rather than name. 
    task :second, :third, :fourth do |t, args| 
        puts args.inspect # => '{ :third => "1", :fourth => "2" }' 
    end 
    
    $ rake first[1, 2] 
    
  3. 另一種解決方案是猴子補丁犁耙的主要應用對象Rake::Application
    並用它來存儲任意值:

    class Rake::Application 
        attr_accessor :my_data 
    end 
    
    task :first => :second do 
        puts Rake.application.my_data # => "second" 
    end 
    
    task :second => :third do 
        puts Rake.application.my_data # => "third" 
        Rake.application.my_data = "second" 
    end 
    
    task :third do 
        Rake.application.my_data = "third" 
    end 
    
    $ rake first 
    
0

設置屬性似乎是一個魅力的工作了。

只要確保將任務依賴關係設置爲設置所需屬性的任務即可。

# set the attribute I want to use in another task 
task :buy_puppy, [:name] do |_, args| 
    name = args[:name] || 'Rover' 
    @dog = Dog.new(name) 
end 

# task I actually want to run 
task :walk_dog => :buy_puppy do 
    @dog.walk 
end 
相關問題