How to generate rake task

Have you ever written your own rake tasks? If you write them very often this post will be very useful for you. I won’t describe what is rake task here because there are a lot of information about it yet. I will tell you how to easy generate rake task.

Rake Task Management Essentials

Recently I have written a book about Rake. It’s called Rake Task Management Essentials. If you like this post’s content and interested in Rake, if you would like to know more about this great tool you can buy it here. I promise that after reading the book you will understand main goals of Rake, how to use it in your development process, daily work or just for fun. You will understand how to refactor and speed up rake tasks. You will be introduced to all Rake’s features by straightforward and practical examples.

Today I found interesting generator in Ruby On Rails. I have never read about it in any post, doc, book or tutorial, I have never seen it in any screencast, I’ve never heart about it from any podcast and I wondered that Google doesn’t tell me nothing about it. So I decided to write about it here.

If you want to write your own rake task you have 2 ways to do it (I thought so before):

  1. Write it from scratch
  2. Copy-paste code from another ready rake task and change code to required

But there is a 3rd way to do it. Just use this rake generator:

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

It will generate scaffold for our new rake task: >lib/tasks/my_namespace.rake

namespace :my_namespace do
  desc "TODO"
  task :my_task1 => :environment do
  end

  desc "TODO"
  task :my_task2 => :environment do
  end
end

It is awesome! And now you can write here your code for new rake tasks.

Let’s make sure these rake tasks are exist and we are able to use them:

$ rake -T | grep my_namespace
rake my_namespace:my_task1  # TODO
rake my_namespace:my_task2  # TODO

Perfect! As you can see it is very easy to write your own rake task. It is easier as you do it before. Thanks for reading!