When developing Rails apps, it is inevitable to automate processes like submitting sitemaps, removing old records and more. Rake Tasks are the default way of doing it. But what should you do and shouldn’t do in your Rake tasks ?
First lets create our rake task:
The namespace lets us group common tasks under one common name while the task itself is our actual task which should be as specific as possible. Great so we have our task, now lets go over the two most used commands:
Rake Task Structure
The generated rake file reflects the command we used to generate it:
- namespace: group common tasks
- desc: describe the task’s use
- task: our ruby code to execute
Sometimes we have to execute other tasks before running our task. We can do this by adding a prerequisite array:
Great we can run tasks before running ours but we can also run tasks inside our task:
What we should do in our Tasks
Use good descriptions
When writing rake tasks it is important to give them a great description because weeks or even months from now our idea is not as clear as it used to be and if we can’t decipher our intention who can ?
Plus when we list our tasks, the description shows up right beside our task name:
Use Namespaces
Common tasks should be grouped under a common namespace because once more it makes it clear what we are doing:
Create folders for each namespace
Create a folder for each namespace and place your tasks inside. Mainly because it becomes very unclear