[英]How do I run rake tasks within my rails application
What I want to do: 我想做的事:
In a model.rb, in after_commit, I want to run rake task ts:reindex 在model.rb中,在after_commit中,我想运行rake task ts:reindex
ts:reindex is normally run with a rake ts:index ts:reindex通常使用rake ts:index运行
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代码在请求周期中运行,那么你应该避免通过
system
或任何exec系列(包括反引号)运行rake,因为这将启动一个新的ruby解释器并在每次调用时重新加载rails环境。
Instead you can call the Rake commands directly as follows :- 相反,您可以直接调用Rake命令,如下所示: -
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
Note: in Rails 4+, you'll use Rails.root
instead of RAILS_ROOT
. 注意:在Rails 4+中,您将使用
Rails.root
而不是RAILS_ROOT
。
And then just use SomeModel.run_rake("ts:reindex")
然后只使用
SomeModel.run_rake("ts:reindex")
The key parts here are to require rake
and make sure you load the file containing the task definitions. 这里的关键部分是
require rake
并确保加载包含任务定义的文件。
Most information obtained from http://railsblogger.blogspot.com/2009/03/in-queue_15.html 大多数信息来自http://railsblogger.blogspot.com/2009/03/in-queue_15.html
I had this same issue and couldn't get the accepted answer to work in my controller with a Rails 4 project due to a load file error. 由于加载文件错误,我遇到了同样的问题并且无法通过Rails 4项目获得在我的控制器中工作的接受答案。 This post gave me a working solution:
这篇文章给了我一个有效的解决方案
def restart_search
require 'rake'
spec = Gem::Specification.find_by_name 'thinking-sphinx'
load "#{spec.gem_dir}/lib/thinking_sphinx/tasks.rb"
Rake::Task["ts:stop"].execute
Rake::Task["ts:start"].execute
respond_to do |format|
format.js { head :ok }
end
end
require 'rake'
RailsApp::Application.load_tasks
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
And then just use SomeModel.run_rake("ts:reindex")
. 然后使用
SomeModel.run_rake("ts:reindex")
。
This code automagically loads the Rake tasks for your Rails application without you even knowing how your application is named :) 此代码自动加载Rails应用程序的Rake任务,而您甚至不知道应用程序的命名方式:)
class MySidekiqTask
include Sidekiq::Worker
def perform
application_name = Rails.application.class.parent_name
application = Object.const_get(application_name)
application::Application.load_tasks
Rake::Task['db:migrate'].invoke
end
end
你试过`rake ts:reindex`吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.