Today I Learned

A Zero One initiative

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.

Looking for help? Each developer at Zero One has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.