Emil Loer dot com

The Rake task-killer

Posted on October 15, 2011

If you have a lot of private gems that are packaged using Bundler then there is always the fear of someone accidentaly running rake release and pushing all of your fancy enterprise code to RubyGems. Let’s prevent this from happening!

First, add the following to your Rakefile, just below the require statements.

class Rake::Task
  def kill!
    @actions.clear
    prerequisites.clear
    enhance { puts "This task is not allowed!" }
  end
end

This snippet adds a kill method to all Rake tasks, even those that are defined outside of the Rakefile.

Now, whenever you want to prevent a task from being used you can kill it using the following invocation:

Rake::Task[:release].kill!

When you invoke the release task after calling kill! on it you will be presented with a warning:

$ rake release
This task is not allowed!

Of course you can use it to kill nested tasks too:

Rake::Task[:"db:drop"].kill!

In this example the Ruby on Rails db:drop task is killed.

Replacing tasks

Normally, when you create a task entry for a task that already exists the given block will be appended to the task. This means that vanilla Rake only has the ability to add work to a given task, not replace it.

However, if we clear the actions first and then append a new block to the list of actions (this is what the enhance call does) we can still manage to replace the entire task.

Here’s an example:

class Rake::Task
  def replace &block
    @actions.clear
    prerequisites.clear
    enhance &block
  end
end

Rake::Task[:release].replace do
  puts "Put your own release code here"
end