Search code examples
rubyrake

Alias of task name in Rake


When I need to alias some task's name, how should I do it?

For example, how do I turn the task name:

rake db:table
rake db:create
rake db:schema
rake db:migration

to:

rake db:t
rake db:c
rake db:s
rake db:m

Editing after getting the answer:

def alias_task(tasks)
    tasks.each do |new_name, old_name|
        task new_name, [*Rake.application[old_name].arg_names] => [old_name]
    end
end

alias_task [
    [:ds, :db_schema],
    [:dc, :db_create],
    [:dr, :db_remove]
]

Solution

  • Why do you need an alias? You may introduce a new task without any code, but with a prerequisite to the original task.

    namespace :db do
      task :table do
        puts "table"
      end
      #kind of alias
      task :t => :table
    end
    

    This can be combined with parameters:

    require 'rake'
    desc 'My original task'
    task :original_task, [:par1, :par2] do |t, args|
      puts "#{t}: #{args.inspect}"
    end
    
    #Alias task.
    #Parameters are send to prerequisites, if the keys are identic.
    task :alias_task, [:par1, :par2] => :original_task
    

    To avoid to search for the parameters names you may read the parameters with arg_names:

    #You can get the parameters of the original 
    task :alias_task2, *Rake.application[:original_task].arg_names, :needs => :original_task
    

    Combine it to a define_alias_task-method:

    def define_alias_task(alias_task, original)
      desc "Alias #{original}"
      task alias_task, *Rake.application[original].arg_names, :needs => original
    end
    define_alias_task(:alias_task3, :original_task)
    

    Tested with ruby 1.9.1 and rake-0.8.7.

    Hmmm, well, I see that's more or less exactly the same solution RyanTM already posted some hours ago.