Creating Custom Rake Tasks in a Rails Application
Creating your own custom rake task is pretty easy. For example, maybe you’d like to write your own rake task to do some database management. Here is the basic structure on how to accomplish that.
You can do pretty-much anything you want inside your rake tasks. Here’s a simple base recipe for creating your own.
Step 1: Create something.rake in your application’s lib/tasks directory.
This is pretty easy - just create a blank file there and you’re on your way.

Step 2: Write your rake task.
You’ll write your task (basic structure below) so that it does whatever you want to do (clean sessions out of a database, handle a DB tweak, etc.)

Step 3: Run your rake task
Your task will be available via rake taskname

So let’s get started shall we?
Basic Syntax of a Custom Rake Task
namespace :something do
desc "Write a description of your task here. ALWAYS document!"
task :taskname => :environment do
# Your task will be executed here, just plug it all in.
puts "Hello World!"
end
endWhat That Does…
First, our namespace declaration helps us organize what this pertains to. Maybe you have several mail tasks available. Your namespace might be “mailtasks” for example.
desc "..." always goes right before your task declaration, so that you can later know what your particular task does. Without getting into the huge nag of telling you to document your code, it’s pretty obvious why you need this - to jog your memory later on, and to tell other programmers who are using the rake task.
But the desc "..." doesn’t just show up in the code, oh no. On the command line when this is done, execute rake -T. You’ll see your task in the list and the description next to it. Cool huh?
task :taskname => :environment do
This line has a lot of magic in it. :taskname declares the name of the task. In this example, we’d execute it by first supplying the namespace, and then the task name itself. So it would literally be, rake something:taskname.
The => :environment portion of this is what’s called a dependency. That tells rake to load the Rails environment before executing the task. This is especially important if you’re using your own models in the rake task. Of course “do” denotes the start of the logic itself.
That’s your basic rake task recipe. Now go rake something!