如何将参数从父任务传递给 Rake 中的子任务? [英] How do I pass arguments from the parent task to the child task in Rake?

查看:38
本文介绍了如何将参数从父任务传递给 Rake 中的子任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Rake 脚本,它由带参数的任务组成.我想出了如何传递参数以及如何使任务依赖于其他任务.

I am writing a Rake script which consists of tasks with arguments. I figured out how to pass arguments and how to make a task dependent on other tasks.

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

  • 我可以将参数从父任务传递给子任务吗?
  • 有没有办法将子任务设为私有,这样它们就不能被独立调用?
  • 推荐答案

    我实际上可以想到三种在 Rake 任务之间传递参数的方法.

    I can actually think of three ways for passing arguments between Rake tasks.

    1. 使用 Rake 对参数的内置支持:

    1. Use Rake’s built-in support for arguments:

    # 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]
    

  • 通过 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]
    

  • 另一种解决方案是对 Rake 的主要应用程序对象进行猴子补丁 Rake::Application
    并用它来存储任意值:

  • Another solution would be to monkey patch Rake’s main application object Rake::Application
    and use it to store arbitary values:

    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
    

  • 这篇关于如何将参数从父任务传递给 Rake 中的子任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆