How to extend an existing rake task
There are several ways to do it, but I think the way that makes the change more evident and intetional is using the Rake::Task#enhance method. Lets extend the db:test:clone_structure standard rails task.
With enhance you can add pre-requisites:
task :prereq_1 do # foo end task :prereq_2 do # bar end Rake::Task["db:test:clone_structure"].enhance [:prereq_1, :prereq_2]
The trace will be:
$ rake db:test:clone_structure --trace ** Invoke db:test:clone_structure (first_time) ** Invoke db:structure:dump (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:structure:dump ** Invoke db:test:purge (first_time) ** Invoke environment ** Execute db:test:purge ** Invoke prereq_1 (first_time) ** Execute prereq_1 ** Invoke prereq_2 (first_time) ** Execute prereq_2 ** Execute db:test:clone_structure
Or add behaviors:
task :extra_behavior do # extra end Rake::Task["db:test:clone_structure"].enhance do Rake::Task[:extra_behavior].invoke end
And the trace now will be:
$ rake db:test:clone_structure --trace ** Invoke db:test:clone_structure (first_time) ** Invoke db:structure:dump (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:structure:dump ** Invoke db:test:purge (first_time) ** Invoke environment ** Execute db:test:purge ** Execute db:test:clone_structure ** Invoke extra_behavior (first_time) ** Execute extra_behavior
And you can combine both:
Rake::Task["db:test:clone_structure"].enhance [:prereq_1, :prereq_2] do Rake::Task[:extra_behavior].invoke end