Tuesday, November 10, 2009

Writing rake task in rails with namespace, parameters

by Sandip Ransing 0 comments

Rake tasks itself defines that “they are bunch of ruby code that performs some task.” Rake tasks are placed in lib/tasks directory of application and files have .rake extension. There are many lovable tasks defined in rails. read more Rake tasks are executed from console. Benefit of writing rake task are Testing of code Scheduled rake tasks ( backgroundRb and scheduled tasks using cron ) Simplifies code Lets, understand what is code inside rake tasks.


Simple greet rake task
 
# lib/tasks/welcome.rake
task :greet do
  puts “Hello !!”
end

## Execute task
rake greet


Adding description to rake task
 
# lib/tasks/welcome.rake
desc “This is new style of greet”
task :greet do
  puts “Hello !!”
end
## Execute task
rake greet

Adding namespace to rake tasks

It's nothing but prefix that takes while executing rake task. Benefit of adding namespace is to categories similar rake tasks.
 
# lib/tasks/welcome.rake
namespace :introduction do
desc “This is one style of introduction”
task :greet do
  puts “Hello !!”
end
desc “This is 2nd style of introduction”
task :hi do
  puts “Hi ”
end
end
## Execute task
rake introduction:greet
rake introduction:hi

Passing arguments to rake tasks
 
# lib/tasks/welcome.rake

namespace :introduction do
desc “This is one style of introduction”
task :greet do
  puts “Hello !!”
end

desc “This is 2nd style of introduction”
task :hi => :enviroment do
  puts “Hi #{ENV['name']}”
end
end
## Execute task
rake introduction:hi name=Raj
read more

blog comments powered by Disqus

About The Author

Sandip is a ruby on rails developer based in pune and also a blogger at funonrails. Opensource contributor and working with Josh software Private Limited. for more info read Follow Sandip on Twitter for updates.

Connect With Me...

Github Projects

@sandipransing Twitter