Is there any way to find out the current rake task?

Is it possible to find out the current rake task in ruby:

# Rakefile task :install do MyApp.somemethod(options) end # myapp.rb class MyApp def somemetod(opts) ## current_task? end end 



Edit

I ask about any global variable that might be requested about this because I wanted to make the application smart for a rake and not change the task itself. I think the application should behave differently when it starts using a rake.

+11
ruby rake
Sep 09 2018-11-11T00:
source share
4 answers

I am thinking about making the app look different when rake launches it.

Is it enough to check caller if it is called from the rake, or do you need and what task?




Hope this is normal when you can modify the rakefile file. I have a version that introduces 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 comments about this:

  • you can add changes to rake to the file and require it in your rake file.
  • starting and setting tasks are test tasks for checking if there is more than one task.
  • I did only small tests for side effects. I could imagine that in a real production situation there are problems.
+3
Sep 20 2018-11-21T00:
source share

This question was asked in several places, and I did not think that any of the answers was very good ... I think the answer is to check Rake.application.top_level_tasks , which is a list of tasks that will be performed. Rake does not necessarily run just one task.

So in this case:

 if Rake.application.top_level_tasks.include? 'install' # do stuff end 
+14
Jun 26 '13 at 19:56
source share

Best to use a 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 
+10
Sep 09 '11 at 17:51 on
source share

The tasks of rake are not magical. This is like calling a method.

The easiest (and clearest) way to accomplish what you want is to simply pass the task to 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 
+1
Sep 09 '11 at 16:48
source share



All Articles