Wednesday, 16 July 2014

Invoke a rake task multiple times from another

To invoke a rake task within another, one can do the following:

Rake::Task['namespace:task_name'].invoke

However, if you need to run a task multiple times, the following will not work.

n.times do
    Rake::Task['namespace:task_name'].invoke
end

It only executes the task once. This behaviour is useful when you are loading dependent tasks. For example, if there are two tasks that depend upon :environment task, this behaviour ensures :environment is loaded only once. However, the above code is written with a different intension. To make it work correctly, the rake task has to be re-enabled. The way to do it is as follows:

n.times do
    task = Rake::Task['namespace:task_name'].invoke

    task.reenable
    task.invoke
end