Showing posts with label Rake tasks. Show all posts
Showing posts with label Rake tasks. Show all posts

Sunday, March 15, 2009

Calling RAKE tasks

The syntax for calling a Rake task within rails env,

Rake::Task[TASK_NAME].invoke

If you need to call a rake task from a standalone ruby script, then do remember to include 'rake' files.

Bellow I have provided an usage on how to call a RAKE task from a rufus scheduler script.

My scheduler script is placed inside /lib folder

Also the script will fail to locate your rake task if just call a RAKE method without loading the RAKE file ( the .rake file in which you have your tasks defined ).

So, make sure you load your rake task files.

USAGE
 
require 'rubygems'
require 'rake'
require 'rufus/scheduler'

load File.join( RAILS_ROOT, 'lib',
'tasks', 'my_task.rake')


scheduler = Rufus::Scheduler.start_new

scheduler.cron("0 17 * * 0") do
Rake::Task["maintenance:delete_order_files"].invoke
end

This when triggered will call 'delete_order_files' task defined in a .rake file called MY_TASK.RAKE having namespace 'MAINTENANCE'

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