One Task Per File, Namespaces Match Directories

Learn about directories matching with the namespaces.

We'll cover the following

Organizing Rake task

To invoke a Rake task, we type bin/rails «task_name». Developers often either need to figure out the task name in order to invoke, or they may see an invocation configured and need to find the source code. These are both unnecessarily difficult if we don’t keep the tasks organized.

For example, if we see that we have a task that runs periodically named db:updates:prod:countries, we can’t just grep for that task name. We have to find :countries or countries: in a file, and then see if the namespace containing it is db:updates:prod. The older an app gets, the more tasks it accumulates and the harder it is to locate code.

The best way we have found to keep Rake tasks organized is as follows:

  • Create a directory structure in lib/tasks that matches the namespaces exactly. In the example above, that means lib/tasks/db/updates/prod/ would be where we’d find the countries task.
  • Name the actual file using the name of the task and place only one task in each file. That means lib/tasks/db/updates/prod/countries.rake would be where the task is defined.
  • Name the task—the last part of the full task name—something explicit and obvious. The example of countries is a terrible name. Try update_list_of_countries instead.
  • Always always always use desc to explain what the task does.

It might seem like overkill, but this will scale very well, and no one is going to complain that they can easily figure out where a task is defined by following a convention. We’ll also point out that our Rails app has no limit on the number of source files it can contain there’s plenty to go aroundOneTaskPerFileNamespacesMatchDirectories.

Beyond this, we’ll need to think about the information architecture of our Rake tasks. This is not easy. Our suggestion is the same one we’ve given many other times in this course, which is to look for a pattern to develop and form a convention around that.

As an example, here is how the lib/tasks directory is structured in an app we are working on right now (we are using the tree command that will make ASCII art of any directory structure):

Get hands-on with 1200+ tech skills courses.