ruby-on-rails – 从Rake任务调用Application Controller功能

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 从Rake任务调用Application Controller功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想从rake任务中调用ApplicationController中的函数.我添加了=> :环境标记,但它只是不想工作.

这是我的剥离代码

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

我的其他控制器一直调用这段代码,没问题.我的Rake任务如何调用代码?这大大简化了,它是一个更大问题的一部分,我想重用更多的代码.

谢谢!!

解决方法

首先,您得到的错误是因为您正在调用ApplicationController.is_admin?未定义,因为您的方法是在ApplicationController的实例上定义的,而不是在ApplicationController类上定义的.

其次,会话的概念(至少对我来说)在rake任务中并没有太多意义.在命令行中没有除用户会话之外的真实会话,这不是您将获得的.

说实话,我不知道从继承ApplicationController或ActionController :: Base的类之外的任何地方调用Controller动作/方法的最佳方法,或者你想要的原因.这些操作/方法专门设计为在请求期间使用,而不是您随时调用的某些操作.如果您确实需要某些东西并且不想重新定义它,请将其放入模型/库中并包含它.

原文链接:https://www.f2er.com/ruby/265485.html

猜你在找的Ruby相关文章