2010-10-05 57 views
2

我疑難解答爲什麼似乎我的ApplicationController的方法並不在我的命名空間中管理區工作,好像當我在一個命名空間,我不能訪問我的ApplicationController的私有方法是,是這樣的對?Authlogic,命名空間和私有方法在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 

感謝您的幫助,

Arne

回答

0

我還沒有使用authlogic,但也許你nee d改變

require_user 

before_filter :require_user 
1

你應該在管理:: DashboardController使用的before_filter:

class Admin::DashboardController < ApplicationController 
    layout 'administration' 

    before_filter :require_user 

    def index 
    end 
end 
+0

它是一個很好的做法,以保持CURRENT_USER作爲一個公共的方法?有沒有與此相關的風險?我想像其中一個受歡迎的教程使得它們變得私密而非公開,因爲我發現我也犯了這個錯誤。 – Mittenchops 2012-07-19 22:41:15

+0

@Voldy你錯了第一點。這不是方法可見性在Ruby中的工作方式。該教程是錯誤的。您可以從子類中訪問私有方法,只需在irb上嘗試即可。在ruby中,private意味着你不能使用接收者,只需從包含任何子類實例上下文的實例上下文進行訪問。 – grzuy 2012-10-14 16:50:02

+0

@grzuy你是對的。感謝您指點。 – Voldy 2012-10-14 17:26:22