Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass arguments from the parent task to the child task in Rake?

Tags:

ruby

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
  • Can I pass the arguments from the parent task to the child tasks?
  • Is there a way to make the child tasks as private so they can't be called independently?
like image 537
Haseeb Khan Avatar asked Apr 04 '10 15:04

Haseeb Khan


People also ask

How do I run a rake file?

Go to Websites & Domains and click Ruby. After gems installation you can try to run a Rake task by clicking Run rake task. In the opened dialog, you can provide some parameters and click OK - this will be equivalent to running the rake utility with the specified parameters in the command line.


1 Answers

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

  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]
    
  2. Directly invoke tasks via 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. 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
    
like image 127
rubiii Avatar answered Oct 16 '22 07:10

rubiii