Call Controller from Rake Task

Calling a controller action from a rake task

You're approaching it from the wrong end. Instead of trying to hit http endpoint from within the app, just perform the logic from that action directly.

You are in the app environment already and have access to all of the code! You don't need the http interface.

If you insist on using http interface, though, you can do this the same way you'd get an external api endpoint. Using Net::HTTP, for example.

Call Application Controller functions from Rake task

First, the error you are getting is because you are calling ApplicationController.is_admin? which isn't defined because your method is defined on instances of ApplicationController, not on the ApplicationController class.

Second, the concept of session (at least to me) doesn't really make too much sense in a rake task. There are no real sessions other than your user's session at the command line which is not what you would be getting.

To be honest, I don't know the best way for going about calling a Controller action/method from anywhere outside of classes that inherit from ApplicationController or ActionController::Base, or why you would want to. Those actions/methods are specifically designed to be used during a request, not some action that you call whenever. If you really need something and don't want to redefine it, put it in a model/library and include it.

rake task has to run a controller method every 2 minutes

now its working for me....

i moved method implementation to "downloader.rake" file which added at lib/tasks.
the code in downloader.rake is

namespace :downloader do
desc "download a file"
task:downloading => :environment do
Rails.logger.info("message from task")
.......method implementation........
end
end

i scheduled the above implementation in "schedule.rb" in config file

every 2.minutes do
rake "downloader:downloading"
end

here "downloader" is the name of the rake file and "downloading" is the task name



Related Topics



Leave a reply



Submit