Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Rake Task Description from within Task

Tags:

ruby

rake

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
like image 599
Kevin Sylvestre Avatar asked Jan 08 '12 20:01

Kevin Sylvestre


People also ask

What is a Rakefile?

A Rakefile contains executable Ruby code. Anything legal in a ruby script is allowed in a Rakefile. Now that we understand there is no special syntax in a Rakefile, there are some conventions that are used in a Rakefile that are a little unusual in a typical Ruby program.

What is rakefile in Ruby?

Rake is a tool you can use with Ruby projects. It allows you to use ruby code to define "tasks" that can be run in the command line. Rake can be downloaded and included in ruby projects as a ruby gem. Once installed, you define tasks in a file named "Rakefile" that you add to your project.


2 Answers

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.

like image 84
knut Avatar answered Sep 22 '22 04:09

knut


Having a similar problem, that I wanted to show the user a customized help screen. The answer here helped me a lot.

It is very important that

Rake::TaskManager.record_task_metadata = true

is done before the first definition of tasks.

Then you can do

Rake.application.tasks.each do |t|
    printf("%-}s  # %s\n",
           t.name_with_args,
           t.comment)
  end

Details can be found by investigating https://github.com/jimweirich/rake/blob/master/lib/rake/application.rb#L284

like image 35
Bernhard Avatar answered Sep 22 '22 04:09

Bernhard