Skip to content

Instantly share code, notes, and snippets.

@ngan
Created August 13, 2010 14:32
Show Gist options
  • Save ngan/522973 to your computer and use it in GitHub Desktop.
Save ngan/522973 to your computer and use it in GitHub Desktop.
# This method provides a way for overriding an existing rake task. Currently,
# in Rake, there is no way to override--only append.
#
# Example usage:
#
# namespace :db do
# override_task :migrate => :environment do
# puts "Do some stuff before!"
#
# # Call the original task
# Rake::Task["db:migrate:original"].invoke
#
# puts "Do some stuff after!"
# end
# end
def override_task(*args, &block)
# Use resolve_args (provided by Rake::Application to break down arguments
# usually provided to #task.
name, params, deps = Rake.application.resolve_args(args.dup)
# Look up the task that we're about to override.
task = Rake::Task[name]
# Make sure that the task we're overriding is defined.
raise "Task #{name} must be defined to override" unless task
# Create a new task that is an alias of the current one, appending ":original"
# onto the task name. Copy over the arg_names, prerequisites and actions
# of the original task.
aliased_task = task.application.intern(task.class, "#{task.name}:original")
aliased_task.set_arg_names(task.arg_names)
aliased_task.prerequisites.each do |prerequisite|
aliased_task.enhance(prerequisites)
end
aliased_task.actions.each do |action|
aliased_task.enhance(&action)
end
# Clear out the task.
task.clear
# Set our new arg_names and enhance the task with our prerequisite and action.
task.set_arg_names(params)
task.enhance(deps, &block)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment