80

I'd like to run a rake task in my controller. Is there any way to do this?

4

4 回答 4

64

我同意 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

您可以在初始化程序中要求 'rake' 和 .load_tasks。

于 2012-03-30T13:25:47.610 回答
61

我觉得在代码中调用 rake 任务不是很好的风格。我建议将要执行的任务的代码放在 rake 任务之外的某个地方,并让 rake 任务调用此代码。

这不仅具有易于调用外部 rake 的优点(这是您想要的),而且还使测试 rake 任务变得更加容易。

于 2009-07-23T07:49:17.037 回答
19

Instead of trying to call a rake task in a controller, call a service objects that contains whatever logic you are trying to execute.

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:

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.

于 2016-03-01T21:10:31.160 回答
16

您可以在控制器中执行此操作:

%x[rake name_task]

with:name_task是你的任务名称

于 2011-08-19T14:37:20.200 回答