Monday 3 June 2013

Rails: Custom Rake Tasks

Rake is a great command line utility for rails. Most rails developers will use it for database migrations.

rake db:migrate

You can also see what rake tasks is available to you by running the following command from the command line.

rake -T

This post is about creating custom rake tasks that you can view with the above command and run to do tasks for your rails application that you would not want to do from within the application because it would take too long.

We start with a simple example by creating a file with a demo.rake extension in the lib/tasks/ folder of your rails app with the following code.

task :hello_world do
  puts 'Hello World!'
end
Now run the command from the command line.
rake hello_world

It should have printed out your puts command. If you run rake -T you will find that it does not list your new task. To do that you have to add a description to your task so that it looks like this.

desc "Prints Hello World!"
task :hello_world do
  puts 'Hello World!'
end

It will now be in the list when you run rake -T. You saw that a rake task is called by its task name and not file name. You can have multiple tasks in the same rake file with its own desc and task block. You don't wrap the whole file in a block.

I personally use custom rake commands to do db maintenance while offline or to run scripts that collects information from the internet and saves it to database. To have a rake task interact with your rails app you have to load the rails environment and you do that by loading it is a dependency. You add => environment after you task name. Here is an example rake file that resets all the products or users in your db. This saves you having to drop into rails console to methods on models.

desc "Deletes all products in db"
task :reset_products => :environment do
  Product.destroy_all
end

desc "Deletes all users in db"
task :reset_users => :environment do
  User.destroy_all
end

I use this mainly on my development machine while rails server is not running. Some of my tasks do scraping jobs and can take hours to run. If you ran that from within the app your app would have been frozen waiting for the job to finish. Also be careful to run a rake task that saves to the database while the app is running as it can lock the db (when using webrick).

No comments:

Post a Comment