【问题标题】:Authlogic, Namespace and private methods in ApplicationControllerApplicationController 中的 Authlogic、Namespace 和私有方法
【发布时间】:2010-10-05 18:04:03
【问题描述】:

我正在排除为什么我的 ApplicationController 的方法似乎在我的命名空间管理区域中不起作用,并且当我在命名空间中时我似乎无法访问我的 ApplicationController 的私有方法,对吗?

如果是这样,在我的命名空间控制器中重用类似 Authlogic 的示例 ApplicationController 方法的最佳实践是什么?我可以轻松地将这些方法复制并粘贴到 AdminController 或其他东西上,我也可以取消私有这些方法 - 但这似乎不是一个好方法。

这是来自 Authlogic(和我的)的示例 ApplicationController 的样子:

class ApplicationController < ActionController::Base
  protect_from_forgery

  helper_method :current_user_session, :current_user

  private
    def current_user_session
      return @current_user_session if defined?(@current_user_session)
      @current_user_session = UserSession.find
    end

    def current_user
      return @current_user if defined?(@current_user)
      @current_user = current_user_session && current_user_session.user
    end  

    def require_user
      unless current_user
        store_location
        flash[:notice] = "You must be logged in to access this page"
        redirect_to new_user_session_url
        return false
      end
    end

    # and some more methods here...

end

这就是我在命名空间中继承它的方式:

class Admin::DashboardController < ApplicationController
  layout 'administration'

  require_user # fails

  def index
  end

end

感谢您的帮助,

阿恩

【问题讨论】:

    标签: ruby-on-rails namespaces ruby-on-rails-3 authlogic


    【解决方案1】:

    你应该在 Admin::DashboardController 中使用 before_filter:

    class Admin::DashboardController < ApplicationController
      layout 'administration'
    
      before_filter :require_user
    
      def index
      end
    end
    

    【讨论】:

    • 将 current_user 保留为公共方法是一种好习惯吗?是否存在与此相关的风险?我想某个地方的流行教程之一将它们设为私有而不是公开,因为我发现我也犯了这个错误。
    • @Voldy 你的第一点就错了。这不是方法可见性在 ruby​​ 中的工作方式。那个教程是错误的。您可以从子类中访问私有方法,只需在 irb 上尝试。在 ruby​​ 中,私有意味着您不能使用接收器,只能从实例上下文访问,其中包括任何子类实例上下文。
    【解决方案2】:

    我没用过authlogic,但也许你需要改变

    require_user
    

    before_filter :require_user
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 2012-02-18
      • 1970-01-01
      相关资源
      最近更新 更多