Search code examples
rubyrakerake-task

Call a Rake task repeatedly


I have a Rake task that calls a number of other Rake tasks, one repeatedly:

task :cycle do
  Rake::Task["db:work"].invoke(0)
  Rake::Task["db:work"].invoke(nil)
end

task :work, [:version,] do |t, args|    
  if args[:version]
    puts " * Migrating to version #{args[:version]}"
  else
    puts " * Migrating to latest version"
  end
end

When I run the cycle task, it only runs the work task once:

$ rake db:cycle
 * Migrating to version 0

I expected this:

$ rake db:cycle
 * Migrating to version 0
 * Migrating to latest version

Is there a way to force Rake to run both tasks?


Solution

  • rake is OSS, btw.

    Rake::Task#invoke checks that the task was not previously invoked and early returns if it was. I do not know much about rake, but resetting this instance variable should do the trick.

    Rake::Task["db:work"].tap do |task|
      task.invoke(0)
      task.instance_variable_set(:@already_invoked, false)
      task.invoke(nil)
    end