Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to know the current rake task?

Tags:

ruby

rake

Is it possible to know the current rake task within ruby:

# Rakefile
task :install do
  MyApp.somemethod(options)
end

# myapp.rb
class MyApp
  def somemetod(opts)
     ## current_task?
  end
end

Edit

I'm asking about any enviroment|global variable that can be queried about that, because I wanted to make an app smart about rake, not modify the task itself. I'm thinking of making an app behave differently when it was run by rake.

like image 836
eloyesp Avatar asked Sep 09 '11 15:09

eloyesp


People also ask

How do I see Rake tasks?

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.

Where are Rake tasks located?

In any Rails application you can see which rake tasks are available - either by running rake -AT (or rake --all --tasks) to see all tasks, or rake -T (or rake --tasks ) to see all tasks with descriptions.

How do you fail a rake task?

You can use abort("message") to gracefully fail rake task. It will print message to stdout and exit with code 1.

How do I run a specific rake task?

Go to Websites & Domains and click Ruby. After gems installation you can try to run a Rake task by clicking Run rake task. In the opened dialog, you can provide some parameters and click OK - this will be equivalent to running the rake utility with the specified parameters in the command line.


2 Answers

This question has been asked a few places, and I didn't think any of the answers were very good... I think the answer is to check Rake.application.top_level_tasks, which is a list of tasks that will be run. Rake doesn't necessarily run just one task.

So, in this case:

if Rake.application.top_level_tasks.include? 'install'
  # do stuff
end
like image 93
colinta Avatar answered Oct 10 '22 04:10

colinta


A better way would be use the block parameter

# Rakefile
task :install do |t|
  MyApp.somemethod(options, t)
end

# myapp.rb
class MyApp
  def self.somemetod(opts, task)
     task.name # should give the task_name
  end
end
like image 13
dexter Avatar answered Oct 10 '22 04:10

dexter