23

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.

4 Answers 4

32

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 
Sign up to request clarification or add additional context in comments.

4 Comments

Brilliant. Just what I was looking for.
Awesome Info.. I have serached for 4 hours. Thank you Very much
Fantastic solution.
Doesn't exactly/necessarily answers the question, but that was good enough for me, so I did this.
14

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 

Comments

3

I'm thinking of making an app behave different when runned by rake.

Is it already enough to check caller, if it is called from rake, or do you need also which task?


I hope, it is ok, when you can modify the rakefile. I have a version which introduce Rake.application.current_task.

# Rakefile require 'rake' module Rake class Application attr_accessor :current_task end class Task alias :old_execute :execute def execute(args=nil) Rake.application.current_task = @name old_execute(args) end end #class Task end #module Rake task :start => :install do; end task :install => :install2 do MyApp.new.some_method() end task :install2 do; end # myapp.rb class MyApp def some_method(opts={}) ## current_task? -> Rake.application.current_task puts "#{self.class}##{__method__} called from task #{Rake.application.current_task}" end end 

Two remarks on it:

  • you may add the rake-modifications in a file and require it in your rakefile.
  • the tasks start and install are test tasks to test, if there are more then one task.
  • I made only small tests on side effects. I could imagine there are problems in a real productive situation.

Comments

1

Rake tasks aren't magical. This is just like any method invocation.

Easiest (and clearest) way to accomplish what you want is to just pass the task into the function as an optional parameter.

# Rakefile task :install do MyApp.somemethod(options, :install) end # myapp.rb class MyApp def somemetod(opts, rake_task = nil) end end 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.