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 !!

6 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 !

Simon Chiang said...

You may also try clearing the prerequisites and actions (no extra methods needed):

task :default do
puts "previous"
end

task(:default).clear_prerequisites.clear_actions

task :default do |t|
puts "current"
end

Without clear:

% rake
previous
current

With clear:

% rake
current

Anonymous said...

TAHNK YOU THIS SOLVED MY PORBLEM

diego.a said...

It solved my problem too. Especially Simon's solution.

Amit Kumar said...

Glad that it helped you.