Writing rake task in rails with namespace, parameters

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 moreRake tasks are executed from console.Benefit of writing rake task areTesting of codeScheduled rake tasks ( backgroundRb and scheduled tasks using cron )Simplifies codeLets, 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

Advertisements

About sandipransing

Web Developer #ruby #rails #JS
This entry was posted in Ruby on Rails and tagged , . Bookmark the permalink.

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