Automating Your Rails Back End

Writing Custom Rake Tasks

Namespacing, Modules, and Meta Tasks

Garrett Bodley
Geek Culture

--

Photo by Tom Byrom on Unsplash

Rake, which stands for “Ruby Make”, is a ruby utility that takes the place of the common Unix make utility. If you’ve worked with rails at all I’m sure you’re familiar with using commands such as rake db:migrate or rake db:rollback to manage your server’s database. These default rake tasks are automatically bundled with your rails install, but you can also write custom rake commands to automate any task of your choosing.

Creating Our Rake File

Your custom rake tasks must be written in a file with a .rake extension which must be located within ./lib/tasks.

touch ./lib/tasks/example.rake

Writing A Task

Declaring a task within our .rake file is very simple

While the description is technically optional, but it’s important to note that tasks without a description will not be listed when entering rake -T in the command line.

To call the above example:

rake something

Organizing Our Tasks

You can view available rake tasks by typing “rake -T” in the command line

If you take a look at the default .rake tasks you’ll see the Rails devs opted to organize things via namespacing. While not technically required, grouping similar functions within a namespace helps to keep your code tidy.

Thankfully, namespacing your custom rake tasks couldn’t be easier:

Which would be called in the command line as follows:

rake custom_task:something

You can also utilize nested namespacing:

And called via command line:

rake custom_tasks:productive:something
rake custom_tasks:unproductive:nothing

Utilizing Modules in Your Rake Tasks

Modules should be included inside of each task and must be required at the top of the file. Including the module inside of the task limits its scope, preventing it from being included for the entirety of your app which could lead to unintentional bugs.

Calling Rake Tasks Within Another Rake Task

You can write meta tasks that call existing rake tasks as well via Rake::Task['your_subtask_name_as_a_string'].execute. It’s important that the string used matches what you would use to call the sub task via the command line. This means a namespaced task must include its namespace when called from inside of a different task.

An Example

Below are custom rake tasks I wrote to automate the scraping behavior of one of my projects. The actual scraping logic is contained within my PicParser module while the various tasks specify the URL and period to scrape. You’ll also notice that I utilize the :environment flag, allowing the PicParser module to access the models used in the rest of my application.

--

--