【问题标题】:Is there a way to know the current rake task?有没有办法知道当前的 rake 任务?
【发布时间】:2011-09-09 15:14:39
【问题描述】:

是否可以在 ruby​​ 中知道当前的 rake 任务:

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

# myapp.rb
class MyApp
  def somemetod(opts)
     ## current_task?
  end
end

编辑

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

【问题讨论】:

    标签: ruby rake


    【解决方案1】:

    这个问题问了好几个地方了,我觉得没有一个答案很好……觉得答案是查Rake.application.top_level_tasks,这是一个列表将运行的任务。 Rake 不一定只运行 一个 任务。

    所以,在这种情况下:

    if Rake.application.top_level_tasks.include? 'install'
      # do stuff
    end
    

    【讨论】:

    • 太棒了。正是我想要的。
    • 很棒的信息.. 我已经搜索了 4 个小时。非常感谢
    • 很棒的解决方案。
    • 不完全/不一定回答这个问题,但这对我来说已经足够好了,所以我做了this
    【解决方案2】:

    更好的方法是使用块参数

    # 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】:

      我正在考虑让一个应用在由 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-modifications 并在您的 rakefile 中要求它。
      • 启动和安装任务是要测试的测试任务,如果有多个任务。
      • 我只对副作用进行了小测试。我可以想象在实际生产情况下会出现问题。

      【讨论】:

        【解决方案4】:

        Rake 任务并不神奇。这就像任何方法调用一样。

        完成您想要的最简单(也是最清晰)的方法是将任务作为可选参数传递给函数。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-07-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-22
          • 2011-12-10
          • 2010-12-24
          相关资源
          最近更新 更多