有没有办法知道当前的佣金任务?
是否有可能知道ruby中当前的rake任务:
# Rakefile task :install do MyApp.somemethod(options) end # myapp.rb class MyApp def somemetod(opts) ## current_task? end end
编辑
我问的是任何可以查询的环境变量全局变量,因为我想让一个应用程序智能化rake,而不是修改任务本身。 我正在考虑让应用程序在rake运行时表现不同。
我正在考虑让一个应用程序在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
两条评论:
- 你可以在一个文件中添加rake-modification并在你的rakefile中需要它。
- 如果有多个任务,则任务启动和安装是要测试的测试任务。
- 我只对副作用做了很小的测试。 我可以想象在真正的生产环境中存在问题。
这个问题已被问到一些地方,我不认为任何答案都非常好…… 我认为答案是检查Rake.application.top_level_tasks
,这是一个将要运行的任务列表。 Rake不一定只运行一项任务。
所以,在这种情况下:
if Rake.application.top_level_tasks.include? 'install' # do stuff end
更好的方法是使用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
耙子任务并不神奇。 这就像任何方法调用一样。
最简单(也是最清晰)的方法来完成您想要的只是将任务作为可选参数传递给函数。
# Rakefile task :install do MyApp.somemethod(options, :install) end # myapp.rb class MyApp def somemetod(opts, rake_task = nil) end end