Custom rake tasks in a Rails project
Now, let's figure out why the custom rake tasks are used in a Rails project. First of all, they are aimed to support tasks that make something recur with the project. For example, this can be generating a sitemap.xml
file for the site, cleaning up old data, backing up the database, sending e-mails in the background, and similar tasks.
In the demonstration, the custom rake tasks in a Rake project have no special steps. Assume that we have orders
in our system and we have to delete them if their status is deleted
. There aren't any special steps to write a custom rake task to solve this problem. Just open the terminal and generate the following rake task:
$ rails g task orders cleanup create lib/tasks/orders.rake
Now open the generated file and write the following code there:
namespace :orders do desc 'Remove old orders with the deleted status' task :cleanup => :environment do Order.where(:status => 'deleted').find_each(&:destroy) ...