Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a controller action from a rake task?

I have a controller action that generates a number of excel reports, this takes about 10 minutes to do. Sometimes I call it from my webapp, which is why it is an action.

But I also want to create a rake task to run this, so I can schedule it to automatically run once a night.

Any way to do this?

like image 236
Janak Avatar asked Mar 24 '10 10:03

Janak


People also ask

How do you call a rake task?

Go to Websites & Domains and click Ruby. After gems installation you can try to run a Rake task by clicking Run rake task. In the opened dialog, you can provide some parameters and click OK - this will be equivalent to running the rake utility with the specified parameters in the command line.

How do you abort a rake task?

If you meant exiting from a rake task without causing the "rake aborted!" message to be printed, then you can use either "abort" or "exit".


2 Answers

Can you handle the report generation from your models? Models should be doing most of the work anyway and can be accessed from Rake tasks:

task :reports => :environment do
  ...
  # Do stuff with your models.
end
like image 67
John Topley Avatar answered Oct 19 '22 00:10

John Topley


I think you'll have to move your code into your model. Since it's bad to put knowledge about output rendering in models, I'd suggest putting all the business logic and data manipulation in the model, but then put the rendering code in your rake task. That would make the rake task analogous to the controller used on the web - maintaining separation of concerns.

You can look at ActionView::Base and work from there to figure out how to trigger rendering of templates.

like image 3
edebill Avatar answered Oct 18 '22 23:10

edebill