Wednesday, February 18, 2009

Raking in rails

Rake tasks are one of the most power but still under utilized part in rails.

Building rake tasks makes in much easier for manual execution of scripts and plays a big role when scheduling a job.

We might have taken the command 'rake db:migrate' lightly, but it is the time to explore the components behind this.

'Rake --tasks ' lists the available tasks that can be performed by rake

We can create our now Rake tasks by creating .rake files in side lib/tasks dir in rails app.

Introducing NAMESPACE and TASK

TASK : This block defines what actually you want your ruby code to perform.
 
task :my_first_rake_task do

puts "This is my first rake code"

end

save this sample code in lib/tasks with any name ( with rake ext. )

Now, in cmd run 'rake my_first_rake_task'

...... existed!?? theres still more......

NAMESPACE

To manage your tasks in a better/ logical way you can bind them to a NAMESPACE

USAGE
 
namespace :test do
task :my_first_rake_task do

puts "This is my first rake code"

end
end


in CMD run rake test:my_first_rake_task

Description

Now that you have learned how to create a rake task, Next question is ........ how to give description for the task you have created????

simple...

use desc
 
namespace :test do
desc "This is a simple example to show the usage of rake tasks in rails"
task :my_first_rake_task do

puts "This is my first rake code"

end
end

In CMD type RAKE --tasks

one of the entry in the list will be

rake test:my_first_rake_task #This is a simple example to show the usage of rake tasks in rails

No comments: