Is there a way to know the current rake task?

2019-02-12 01:56发布

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.

标签: ruby rake
4条回答
家丑人穷心不美
2楼-- · 2019-02-12 02:18

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
查看更多
再贱就再见
3楼-- · 2019-02-12 02:31

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
查看更多
太酷不给撩
4楼-- · 2019-02-12 02: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
查看更多
聊天终结者
5楼-- · 2019-02-12 02:36

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.
查看更多
登录 后发表回答