Search code examples
rubyrake

Access Rake Task Description from within Task


Within a rake task how does one query the description? Something that would give:

desc "Populate DB"
task populate: :environment do
  puts task.desc # "Populate DB"
end

Solution

  • taskmust be defined as a parameter for the task-block.

    desc "Populate DB"
    task :populate do |task|
      puts task.comment # "Populate DB"
      puts task.full_comment # "Populate DB"
      puts task.name # "populate "
    end
    

    Edit: This solution works with rake 0.8.7. At least rake 0.9.2.2 need an additional Rake::TaskManager.record_task_metadata = true (I checked only this two versions).

    A stand alone ruby-script with adaption:

    gem 'rake'    #'= 0.9.2.2'
    require 'rake'
    
    #Needed for rake/gem '= 0.9.2.2'
    Rake::TaskManager.record_task_metadata = true
    
    desc "Populate DB"
    task :populate do |task|
      p task.comment # "Populate DB"
      p task.full_comment # "Populate DB"
      p task.name # "populate "
    end
    
    if $0 == __FILE__
      Rake.application['populate'].invoke()  #all tasks
    end
    

    Reason: in rake/task_manager.rb line 30 (rake 0.9.2.2) is a check

      if Rake::TaskManager.record_task_metadata
        add_location(task)
        task.add_description(get_description(task))
      end
    

    The default false is set in line 305.

    .comment vs .full_comment

    For those wondering, .comment prints the first line and .full_comment will print all lines (for multi-line desc), with new lines indicated with \n in the returning String.

    See the docs here: