如何在 Rails 应用程序中运行 rake 任务 [英] How do I run rake tasks within my rails application

查看:39
本文介绍了如何在 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

这篇关于如何在 Rails 应用程序中运行 rake 任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆