Sunday, July 6, 2008

Remove rake tasks

Ever tried over-riding rake task ?

I tried to over-ride and I found that the default always gets called after your implementaion.

Here is what I tried doing:

namespace :db do
  namespace :test do
    task :prepare do |t|
        puts "Skipping Preparing database for Oracle"
    end
  end
end

But the default db:test:prepare was always getting called.

To solve the probelm:

Inside your Rakefile just below you require the rake modules put the following code.

Rake::TaskManager.class_eval do
  def remove_task(task_name)
    @tasks.delete(task_name.to_s)
  end
end

def remove_task(task_name)
  Rake.application.remove_task(task_name)
end
remove_task 'db:test:prepare'

namespace :db do
  namespace :test do
    task :prepare do |t|
      puts "Skipping Preparing database for Oracle"
    end
  end
end

Voila, the italicized code to override the default rake tasks worked.

Hope this helps !!

2 comments:

pragmatig said...

same a bit cleaner/readable imo
module Rake
def self.remove_task(task_name)
Rake.application.instance_variable_get('@tasks').delete(task_name.to_s)
end
end

Amit Kumar said...

Nice !! Thanks for your comments !