Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Application Controller functions from Rake task

I want to call a function in my ApplicationController from a rake task. I've added the => :environment tag, but it just doesn't want to work.

Here is my stripped down code-

lib\taks\autoscrape.rake:
 desc "This task will scrape all the movies without info"
  task(:autoscrape => :environment) do
    require 'application'  #probably extraneous
    require File.dirname(__FILE__) + '/../../config/environment' #probably extraneous
    unless ApplicationController.is_admin?
      logger.error = "Sorry, you're not allowed to do that"
      return
    end


app\controller\application_controller.rb:
class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time

  def is_admin?
        session[:is_admin] && session[:is_admin] > 0
  end
end

result:
rake scrape:autoscrape --trace
** Invoke scrape:autoscrape (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute scrape:autoscrape
rake aborted!
undefined method `is_admin?' for ApplicationController:Class
E:/Dropbox/My Dropbox/Ruby/moviecat/lib/tasks/autoscrape.rake:11

My other controllers call this code all the time, no problems. How can my Rake task call this code? This is greatly simplified, it is part of a bigger problem, i would like to reuse more code.

Thanks!!

like image 432
rajat banerjee Avatar asked Feb 06 '10 18:02

rajat banerjee


2 Answers

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.

like image 161
theIV Avatar answered Sep 22 '22 03:09

theIV


Create a instance for controller and call the method.method inside the controller should be public method.

Example:

objEmail = EmailController.new

objEmail.message
like image 6
William Richerd Avatar answered Sep 21 '22 03:09

William Richerd