如何在 Rails 应用程序中运行 rake 任务

问题描述:

我想做什么:

在model.rb中,在after_commit中,我想运行rake task ts:reindex

In a model.rb, in after_commit, I want to run rake task ts:reindex

ts:reindex 通常使用 rake ts:index

ts:reindex is normally run with a rake ts:index

如果你希望这个 rake 代码在请求周期内运行,那么你应该避免通过 system 或任何 exec 系列运行 rake(包括反引号),因为这将启动一个新的 ruby​​ 解释器并在每次调用时重新加载 rails 环境.

If you wish this rake code to run during the request cycle then you should avoid running rake via system or any of the exec family (including backticks) as this will start a new ruby interpreter and reload the rails environment each time it is called.

相反,您可以直接调用 Rake 命令,如下所示:-

Instead you can call the Rake commands directly as follows :-

require 'rake'

class SomeModel <ActiveRecord::Base

  def self.run_rake(task_name)
    load File.join(RAILS_ROOT, 'lib', 'tasks', 'custom_task.rake')
    Rake::Task[task_name].invoke
  end
end

注意:在 Rails 4+ 中,您将使用 Rails.root 而不是 RAILS_ROOT.

Note: in Rails 4+, you'll use Rails.root instead of RAILS_ROOT.

然后只需使用 SomeModel.run_rake("ts:reindex")

这里的关键部分是要求 rake 并确保加载包含任务定义的文件.

The key parts here are to require rake and make sure you load the file containing the task definitions.

大部分信息来自http://railsblogger.blogspot.com/2009/03/in-queue_15.html