[Rake-devel] Redefine tasks

Blair Zajac blair at orcaware.com
Fri Oct 21 01:56:39 EDT 2005


The new Ruby on Rails 0.14.1 release supports a lib/tasks/ directory 
where you place *.rake files that get imported after RoR's rake 
definitions.   In 0.13.1, I needed to override some of the targets, such 
as :clone_structure_to_test, with my own specific code, and I would just 
edit the Rakefile.

After doing the 0.14.1 and merging in a ton of changes, I thought, there 
has to be a better way, so I can leave a vanilla RoR Rakefile alone and 
still have my own custom targets.

I first tried just defining the same clone_structure_to_test task, but 
when I ran it, it ran the original RoR task and my new version, not what 
I wanted :)

What I came up was this code, which clears out the original task and 
creates a brand new one.

# Rake allows the same task name to be specified multiple times, where
# each successive task definition appends to a list of actions to
# perform.  Therefore, an application specific task cannot redefine a
# previously defined task.  These methods here allow tasks to be
# redefined and renamed.

module Rake
   class Task

     # Clear all existing actions for the given task and then set the
     # action for the task to the given block.
     def self.redefine_task(args, &block)
       task_name, deps = resolve_args(args)
       define_task(args, &block)

# Clear all existing actions for the given task and then set the
# action for the task to the given block.
def redefine_task(args, &block)
   Rake::Task.redefine_task(args, &block)

# Alias one task name to another task name.  This let's a following
# task rename the original task and still depend upon it.
def alias_task(new_name, old_name)
   Rake::Task::TASKS[new_name.to_s] = 

This way, in a new lib/tasks/clone_structure_to_test.rake, I can use this:

# Delete the original clone_structure_to_test task and create a new
# one that uses the SQL DDL files to set up the database.
desc "Faster replacement for the original :clone_structure_to_test"
redefine_task :clone_structure_to_test => :environment do
   abcs = ActiveRecord::Base.configurations
   `psql --quiet -U "#{abcs["test"]["username"]}" -f db/create.sql 

It would be great if something like this made it into the next Rake release.


Blair Zajac, Ph.D.
<blair at orcaware.com>
Subversion and Orca training and consulting

More information about the Rake-devel mailing list