2011-12-05 42 views
0

我搬到一個應用程序使用的ActiveResource和我發現,我需要重新考慮我教過自己做一些事情的方式,我在尋找這是最好的方式。如何保持一個變量方便跨多個控制器

例如,我需要保持我已經在applicationcontroller.rb作爲

@current_account ||= Account.where(etc etc) 

做了一定範圍內的查詢方便發言權@current_account。這對於AR來說並不是那麼有用,因爲每次都調用API。我想最大限度地減少對API的調用(特別是我有其他更昂貴的調用,我不想在每個查詢上運行,我想運行一次,並保持它們方便)

那麼,什麼是Rails辦法?我必須在某個範圍內通過一個AR調用將一個AR調用保存在ApplicationController中,而不需要每次都寫出來(或者每次調用API,或者將其放入用戶可訪問的會話中因爲它不完全是文本/字符串,它是我需要使用的對象)。

我很好奇別人怎麼做,我是否應該或不應該這樣做,什麼是正確的幹法,等等。因此,這是有點開放式的。

理解的任何輸入。

+0

停止問重複的問題:http://stackoverflow.com/questions/8370514/activeresource-caching – sethvargo

+0

這是爲了有Rails應用程序編程的範圍內更廣泛的範圍,所以沒有。花一些時間閱讀而不是淺度掃描。 – blueblank

回答

1

這是最好的這種行爲創建一個模塊:

module CustomAuth 
    def self.included(controller) 
    controller.send :helper_method, :current_account, :logged_in? 
    end 

    def current_account 
    # note the Rails.cache.fetch. First time, it will 
    # make a query, but it caches the result and not 
    # run the query a second time. 
    @current_account ||= Rails.cache.fetch(session[:account_id], Account.where(...)) 
    end 

    def logged_in? 
    !current_account.nil? 
    end 
end 

然後,確保Rails的加載了這個文件(我把礦./lib/custom_auth.rb),所以添加到config.autoload_paths./config/application.rb

# ./config/application.rb 
... 
config.autoload_path += %W(#{config.root}/lib) 
... 

導入CustomAuth模塊到您的application_controller.rb

class ApplicationController < ActionController::Base 
    include CustomAuth 
    protect_from_forgery 

    ... 
end 

最後,至關重要的:重新啓動服務器

注意:您可以添加額外的方法到custom_auth.rb。如果您重新啓動服務器,它們將可用。這些方法也可在視圖中使用,因此您可以在視圖內調用current_account.name

+0

這是我知道的「DRYest」方式。您將所有身份驗證命名空間放在一個模塊中。你並沒有在認證邏輯等方面混淆'application_controller.rb'。 – sethvargo

相關問題