Run the rake command in the controller

I want to run the rake task in my controller. Is there any way to do this?

+63
ruby ruby-on-rails rake
Jul 23 '09 at 7:18
source share
4 answers

I agree with ddfreynee, but if you know what you need, the code may look like this:

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 

Instead, you can require "rake" and .load_tasks in the initializer.

+53
Mar 30 2018-12-12T00:
source share

I do not think it is a good style to call the rake command in code. I recommend putting the code for the task that you want to run somewhere outside of the rake task, and forcing the rake command to call that code.

This not only has the advantage that it is easy to call an external rake (this is what you need), but also makes it easier to check the rake task.

+50
Jul 23 '09 at 7:49
source share

You can do this in your controller:

 %x[rake name_task] 

c: name_task - the name of your task

+16
Aug 19 '11 at 2:37 a.m.
source share

Instead of trying to invoke the rake command in the controller, call the service objects that contain any logic that 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, call the service object as well:

 namespace :example do desc 'important task' task :important_task do SomeServiceObject.call end end 

If you are not familiar with service objects, these are just old ruby ​​classes that do some work. If you are trying to call some of the rake jobs by default (i.e.: db: migrate), I would highly recommend not doing this from the controller.

+7
Mar 01 '16 at 21:10
source share



All Articles