views:

193

answers:

1

I am new to the world of Rake and currently writing a Rake Script which consists of various tasks depending on the arguments passed to it on runtime.

From some Tutorials over the web, I figured out how to pass parameters to the Script as well how to make a task which is dependent on other subtasks.

For reference, I have mentioned a sample below:

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

Following is what I want to achieve:

  1. I want to pass the arguments passed to the parent task to the child tasks. Is it allowed?
  2. Is there a way I can make the child tasks as private so they can't be called independently?

Thanks in advance.

A: 

I can imagine three ways of passing arguments between Rake tasks. Let's start with the most ugly one.
I do not recommend doing this! Use Rake::Task#invoke to pass arguments to another task:

task :first, :one, :two do |t, args|
  puts args.inspect  # => '{ :one => "1", :two => "2" }'
  task(:second).invoke(args[:one], args[:two])
end

task :second, :three, :four do |t, args|
  puts args.inspect  # => '{ :three => "1", :four => "2" }'
end

# invoke via:
rake first[1, 2]

An alternative (and better) solution would be to monkey patch Rake's main application object Rake::Application and store values in there:

class Rake::Application
  attr_accessor :whatever
end

task :first => :second do
  puts Rake.application.whatever  # => "second"
end

task :second => :third do
  puts Rake.application.whatever  # => "third"
  Rake.application.whatever = "second"
end

task :third do
  Rake.application.whatever = "third"
end

# invoke via:
rake first

Probably the best solution is to keep the names of arguments and they will be passed automatically:

task :first, [:one] => :second do |t, args|
  puts args.inspect  # => '{ :one => "one" }'
end

task :second, :one do |t, args|
  puts args.inspect  # => '{ :one => "one" }'
end

# invoke via:
rake first[one]
rubiii