Rake Tasks

With any web application, you will find yourself needing to run ‘behind-the-scenes’ tasks. In the .NET world, I often found myself writing scheduled tasks to run on app servers, or utilizing Taskie to accomplish these goals. But with Ruby on Rails, you’ll find yourself writing Rake tasks.

Rails contains a Rakefile in its root directory. By default, if you run the following command in the terminal while in your Rails root directory, you’ll run the specified rake task:

rake name_of_task

But where do these tasks live? The answer is the lib/tasks directory in your rails application. Within this folder, you can add any number or rake task files with the prefix of .rake. Within these files, you can add a task like so:

desc "A really basic rake task"
task :do_basic_stuff do
 puts "I just did some really cool but basic stuff!"

In the terminal, if you were to run rake do_basic_stuff, you’d see the output described by the above task.

If you want to access your rails environments (object, models, ect…), you’ll need to add the :environment attribute to your task. In the above example, your task would begin with:

task :do_basic_stuff => :environment do

There are a lot of other cool features you can utilize with your rake tasks, but rather than go over them here, I’d highly recommend you watch the railscast on the subject. Afterwards, you should be writing rake tasks like a boss!

Tagged , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: