Wednesday, May 13, 2009

Running the same rake task more than once

While writing some rake tasks, I found out that you cannot run another task more than once in your task.  Example:
task :test do |t|
Rake::Task["log:clear"].invoke
# do something to add to the log file
Rake::Task["log:clear"].invoke
end

No errors will occur, but the second log:clear will not get run. All rake tasks work like this. I'm not really sure of the reason why this capability was put in rake, but rake keeps track of when each task gets run and only allows a task to be run once within the same rake call. But, to get around this, you can call reenable on the task after it's invoked, and then the task can be used again. Example -
task :test do |t|
Rake::Task["log:clear"].invoke
Rake::Task["log:clear"].reenable
# do something to add to the log file
Rake::Task["log:clear"].invoke
end

The second log:clear will now run correctly. Another wonderfully documented feature of Ruby....

3 comments:

JP said...

It seems to work fine for me if you use "execute" instead of "invoke".

Bealer said...

Nice post, just came across this problem myself. Your solution works perfectly.

Eduardo de Santana Medeiros Alexandre said...

If you are writting a task like that, you call also call the method inside the task:

task "log:clean" do |t,args|
# log:clean action

t.reenable
end