2016-11-07 55 views
1

所以我工作的一大Rails項目。有爲數衆多的使用的before_filter設置@current_user變量類(其實有一噸的這些的before_filter其他變量的方法,但是我用這一個爲例):Rails最佳實踐:使用before_filter或application_controller輔助方法?

before_filter :current_user 

哪調用應用程序控制器的使用current_user方法:

class ApplicationController < ActionController::Base 

    def current_user 
     @current_user ||= session[:user_id].present? ? User.includes(:memberships).find(session[:user_id]) : nil 
    end 

另一種選擇是使用application_controller helper方法:

class ApplicationController < ActionController::Base 
    helper_method :get_current_user 

    def get_current_user 
     @current_user ||= session[:user_id].present? ? User.includes(:memberships).find(session[:user_id]) : nil 
    end 

然後我全部更換在應用程序與到輔助方法的調用@current_user引用:

get_current_user 

這保證了方法僅被調用的方法或在需要的地方的意見,對不對?使用before_filter有沒有性能優勢?

+0

沒有必要把它稱爲'get_current_user'。在典型的Ruby代碼中,'get_'部分是多餘的。這裏唯一的區別是你正在強制加載它,這種方式打敗了懶加載的目的。 – tadman

回答

1

在你的情況下,兩個行爲以同樣的方式,並且在你得到的結果相同 - 緩存實例變量@current_user

helper_method

聲明一個控制器方法作爲輔助。例如,下面的 使得CURRENT_USER和LOGGED_IN?提供給 視圖控制器方法

before_action(因爲before_filter已棄用):

追加前行動

由於記憶化的回調被使用的結果是在兩種情況下相同。

before_action不同的是,您實際上在每次調用任何操作時調用方法,而helper_method只是爲您提供幫助。如果兩個執行的邏輯更復雜,的確會有性能差異 - before_action會比較消耗資源。

P.S.兩件事情不同,它的用途是不同的,你不能真正地比較它們。

+0

好的,這很有幫助。我沒有編寫應用程序,並且有很多不同的控制器需要TON(其中一些通過使用'except'或'only'限定before_filter來過濾)。所以它只是接縫機給我使用的輔助方法,必要時調用,而不是添加before_action方法,這可能會或可能不會需要。有沒有辦法保持@current_user實例變量,但將其綁定到application_controller方法,以便它只在需要時才實例化? –

+0

@yeldarb當然,只需將'helper_method'移動到'application_controller.rb',它就可以在所有的控制器中使用 –