Inserting a rake dependency first
Usually, if you’re trying to extend a rake task by adding new dependencies to it you just redefine the task with the new dependency.
namespace :tickle do task :cow => 'relax' end
So if originally tickling the cow would first milk it, typing rake tickle:cow will now:
- Milk the cow
- Relax the cow
- Tickle the cow
If you instead want the relaxing to happen first, you have to go straight at the definition of the task and alter its prerequisites. These prerequisites are just an array of task names, so to make your new task happen first, just insert your task at the beginning.
# fetch the task definition task = Rake::Task['tickle:cow'] # insert our new prerequisite at the beginning task.prerequisites.insert(0, 'relax')
A real-life example of this is if you want to pull some data down before resetting your database with a rake db:migrate:reset. If you define a task like rake data:retrieve and don’t want to remember to do rake data:retrieve db:migrate:reset you can insert data:retrieve as an early prerequisite for db:migrate:reset.
Rake::Task['db:migrate:reset'].prerequisites.insert(0, 'data:retrieve')
And if you have to do this a lot, this may be handy
module Rake
module OrderedPrerequisites
def require_first(*tasks)
prerequisites.insert(0, *tasks)
end
end
class Task
include OrderedPrerequisites
end
end
And now you can do
Rake::Task['db:migrate:reset'].require_first('data:retrieve')