Ruby-on-rails 在控制器中运行 rake 任务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1170148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run rake task in controller
提问by user143482
I'd like to run a rake task in my controller. Is there any way to do this?
我想在我的控制器中运行一个 rake 任务。有没有办法做到这一点?
回答by Grimmo
I agree with ddfreynee, but in case you know what you need code can look like:
我同意 ddfreynee,但如果你知道你需要什么代码可以是这样的:
require 'rake'
Rake::Task.clear # necessary to avoid tasks being loaded several times in dev mode
Sample::Application.load_tasks # providing your application name is 'sample'
class RakeController < ApplicationController
def run
Rake::Task[params[:task]].reenable # in case you're going to invoke the same task second time.
Rake::Task[params[:task]].invoke
end
end
You can require 'rake' and .load_tasks in an initializer instead.
您可以改为在初始化程序中要求 'rake' 和 .load_tasks。
回答by Denis Defreyne
I don't find it good style to call a rake task in code. I recommend putting the code for the task that you want to execute somewhere outside a rake task, and have the rake task call this code.
我觉得在代码中调用 rake 任务不是很好的风格。我建议将要执行的任务的代码放在 rake 任务之外的某个位置,并让 rake 任务调用此代码。
This not only has the advantage of being easy to call outside rake (which is what you want), but it also makes it much easier to test the rake task.
这不仅具有易于调用外部 rake 的优点(这是您想要的),而且还可以更轻松地测试 rake 任务。
回答by Jarrod Spillers
Instead of trying to call a rake task in a controller, call a service objects that contains whatever logic you are trying to execute.
不要尝试在控制器中调用 rake 任务,而是调用包含您尝试执行的任何逻辑的服务对象。
class SomeController < ApplicationController
def whatever
SomeServiceObject.call
end
end
...and then, assuming you are talking about a custom rake task, have it call the service object as well:
...然后,假设您正在谈论自定义 rake 任务,让它也调用服务对象:
namespace :example do
desc 'important task'
task :important_task do
SomeServiceObject.call
end
end
In case you are not familiar with service objects, they are just plain old ruby classes that do a specific job. If you are trying to call some of the default rake tasks (ie: db:migrate) I would highly recommend not doing that sort of thing from a controller.
如果您不熟悉服务对象,它们只是执行特定工作的普通老式 ruby 类。如果您尝试调用一些默认的 rake 任务(即:db:migrate),我强烈建议您不要从控制器中执行此类操作。
回答by olibouli
You can do this in your controller:
您可以在控制器中执行此操作:
%x[rake name_task]
with: name_taskis the name of your task
with:name_task是你的任务名称

