【问题标题】:How do I pass arguments from the parent task to the child task in Rake?如何将参数从父任务传递给 Rake 中的子任务?
【发布时间】:2010-04-04 15:30:54
【问题描述】:

我正在编写一个包含带有参数的任务的 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
  • 我可以将参数从父任务传递给子任务吗?
  • 有没有办法将子任务设为私有,这样它们就不能被独立调用?

【问题讨论】:

    标签: ruby rake


    【解决方案1】:

    我实际上可以想到三种在 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 的主要应用程序对象 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
      

    【讨论】:

      【解决方案2】:

      设置属性似乎也很有魅力。

      只需确保将任务依赖项设置为设置所需属性的任务即可。

      # 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
      

      【讨论】:

        猜你喜欢
        • 2011-07-02
        • 1970-01-01
        • 1970-01-01
        • 2010-10-23
        • 2011-07-05
        • 2016-04-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多