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:hiPassing 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=Rajread more