有没有办法知道当前的佣金任务?

elo*_*esp 15 ruby rake

是否有可能知道ruby中当前的rake任务:

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

# myapp.rb
class MyApp
  def somemetod(opts)
     ## current_task?
  end
end
Run Code Online (Sandbox Code Playgroud)

编辑

我问的是任何可以查询的环境变量全局变量,因为我想让应用程序智能化rake,而不是修改任务本身.我正在考虑让应用程序在rake运行时表现不同.

col*_*nta 20

这个问题已被问到一些地方,我认为任何答案都不是很好...... 认为答案是检查Rake.application.top_level_tasks,这是一个将要运行的任务列表.Rake并不一定只运行一项任务.

所以,在这种情况下:

if Rake.application.top_level_tasks.include? 'install'
  # do stuff
end
Run Code Online (Sandbox Code Playgroud)


dex*_*ter 10

更好的方法是使用block参数

# 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
Run Code Online (Sandbox Code Playgroud)


knu*_*nut 3

我正在考虑让应用程序在由 rake 运行时表现不同。

caller如果从 rake 调用它,检查是否已经足够了,或者您还需要哪个任务?


我希望,当你可以修改 rakefile 时就可以了。我有一个版本介绍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
Run Code Online (Sandbox Code Playgroud)

对此有两点评论:

  • 您可以在文件中添加 rake 修改并在您的 rakefile 中需要它。
  • 任务启动和安装是要测试的测试任务,如果有多个任务。
  • 我只对副作用做了一些小测试。我可以想象在真正富有成效的情况下会出现问题。