Extending Rake Tasks
You can extend rake tasks to add extra functionality.
For example, let’s extend the rails db:migrate
task to automatically include schema migrations and data migrations.
# Inside lib/tasks/db.rake
# Remove the old migrate task
Rake::Task['db:migrate'].clear
namespace 'db' do
# Redefine the migrate task to invoke with data migrations
task migrate: ['migrate:with_data']
end
Now whenever you execute rails db:migrate
, the task will include schema + data migrations.
Additionally, you may want to invoke some extra task after another has been executed. To do this, you can enhance a task like this:
# Inside lib/tasks/db.rake
Rake::Task['db:migrate'].enhance do
Rake::Task['db:do_some_custom_thing'].invoke
end
Now your custom task will be invoked after rails db:migrate
is invoked.