Understanding rake tasks and how to write one

In your RAILS project working directory, when you type rake routes it lists all the routes you made in your application. This rake routes is a 'rake' task which is specified to list all routes in an application. Also there is a task rake db:migrate that runs your migrations. There are many tasks available to you, and they all can be listed using rake -T. But you are not restricted to the tasks listed in rake -T only. You can write your own custom rake tasks also. They will do mundane as well as hefty tasks you will ask them to do for you. But then, how to?

Rake is ruby make. It replaces Unix make and use Rakefile and .rake files to build up a list of tasks. If you are following the lib-spec folder structure we talked about in my last blog, you can simply add a Rakefile in your project folder and there you can add your custom rake tasks. If you are working with RAILS, your tasks are stored in /lib/tasks folder.

You can simply write, in your Rakefile

task :sing do
  puts "Sa Re Ga Ma Pa..."

Or you can generate a Rake task by typing

$ rails g task my_namespace my_task1 my_task2
$ create lib/tasks/my_namespace.rake

For a sample Rakefile with a simple rake task is visit this repo