October 11, 2022•
Rails Quick Tip - 04 - Automating Code with Rake Tasks
Ruby on Rails uses a Ruby gem called rake to generate tasks that otherwise enable your applications to call code with alias commands.
This Rails quick tip walks you through what a rake task looks like and how the Ruby on Rails framework leverages them directly for automating code.
Generating your first task
Rails ships with multiple generators that are accessible via the command line. The idea behind generators is to reduce the need to manually create files and some boilerplate code each time you need it.
You can see a list of all the generators available for your app by running the following:
This should list a bunch of options. Depending on what gems you have installed, there may be a suite of custom options available alongside what comes stock with Rails.
One of the generators included in the framework is called
To generate a new task, you can run this code:
rails generate task my_new_task
Typically your task should describe its intended use case, but as most software people know, naming things is one of the most complex challenges in programming, so do your best here.
A vanilla task file won't have much code inside it. You can namespace the task for best results, so it's easily recognizable from the command line. Including a description is recommended to help let other contributors know what purpose the task serves.
As an example, I generated a new
update_users task by running:
rails g task update_users
The file's name isn't the best, but the general idea is I'm updating something related to a user model. Inside the task, you can write logic that you would like to automate.
# lib/tasks/update_users.rake namespace :users do desc "Update users on the nightly" task update: :environment do puts "Hello world" end end
Previewing what tasks are available
An excellent way for others to know what rake tasks exist for a specific Rails app is through a new command.
This lists all available tasks. Luckily, our new task should be listed, including the description we set.
Why use rake tasks with Rails?
This will vary depending on your app, but I use rake tasks to automate repetitive things.
If you can write a task to call a rake command using some service like Heroku scheduler or a gem like Whenever, you can take a lot of time back and likely deliver a richer experience for your end users.
Rake tasks can be used for something as simple as a boolean toggle to something more complex, like database migrations or API calls to backfill data.