Run rake task in controller

后端 未结 4 1415
情话喂你
情话喂你 2020-11-28 04:33

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

4条回答
  •  無奈伤痛
    2020-11-28 05:03

    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.

提交回复
热议问题