Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if rake task exists from within Rakefile

I'm looking for a way to be able to check if a certain rake task exists from within the Rakefile. I have a task dependency that I only want to include as a dependency if that task is available. In this particular case, the task is only available in a Rails project, but I want my rake tasks to work in a more general Ruby application environment too (not just Rails).

I want to do something like this:

if tasks.includes?('assets:precompile')
  task :archive => [:clean, :vendor_deps, 'assets:precompile']
    ...
  end
else
  task :archive => [:clean, :vendor_deps]
    ...
  end
end

What is the best way to conditionally include a task dependency in a rake task?

like image 820
conorliv Avatar asked Apr 23 '15 14:04

conorliv


People also ask

How do I list a rake task?

You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing rake --tasks . Each task has a description, and should help you find the thing you need.

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.

What is the purpose of the Rakefile available in the demo directory in Ruby?

Rakefile − This file is similar to Unix Makefile, which helps with building, packaging and testing the Rails code.


2 Answers

what about doing something like this? Invoke the task if it exists, as opposed to making it an explicit dependency?

 task :archive => [:clean, :vendor_deps] do 
  Rake.application["assets:precompile"].invoke if Rake::Task.task_defined?('assets:precompile')
   .... 
  end

or even easier. Since specifying the task again allows you to add to it, something like this appears to work as well.

task :archive => [:clean, :vendor_deps] do
    ...
  end
task :archive => "assets:precompile" if  Rake::Task.task_defined?("assets:precompile")

which will conditionally add the dependency on assets:precompile if it is defined.

like image 113
Doon Avatar answered Sep 30 '22 07:09

Doon


You should be able to use task_defined?:

Rake::Task.task_defined?('assets:precompile')
like image 43
Shadwell Avatar answered Sep 30 '22 07:09

Shadwell