2011-11-08 35 views

回答

0

我在我的網站上有一個有趣的需求 - 對不同的主題,不同的頁面可以從同一個url返回。所以我想出了一個名爲「匿名緩存」的解決方案,並且創建了自己的緩存密鑰,包括額外的參數。但我認爲這個解決方案可以給你一些線索。

module AnonymousCache 
    def self.included(base) 
    base.extend(ClassMethods) 
    end 
    module ClassMethods 
    def caches_page_for_anonymous(*pages) 
     before_filter :check_cache_for_anonymous, :only => pages 
     after_filter :cache_for_anonymous, :only => pages 
    end 
    end 
    def check_cache_for_anonymous 
    return unless perform_caching 
    return if logged_in? 
    path = anon_cache_path 

    if content = Rails.cache.read(path) 
     send_data(content, 
     :type => 'text/html;charset=utf-8', :disposition => 'inline') 
     return false 
    end 
    end 
    def cache_for_anonymous 
    return unless perform_caching 
    return if logged_in? 
    path = anon_cache_path 
    @expires_in ||= 1.hour 
    self.class.benchmark "Cached page for guest: #{path}" do 
     Rails.cache.write(path, response.body, :expires_in => @expires_in.to_i) 
    end 
    end 
    protected :check_cache_for_anonymous 
    protected :cache_for_anonymous 
    private 
    def anon_cache_path() 
     path1 = File.join(request.host, current_theme, request.path) 
     q = request.query_string 
     path1 = "#{path1}?#{q}" unless q.empty? 
     path1 
    end 
end 

anon_cache_path方法是我做的頁面緩存規範的鍵。你可以看到我包含current_theme

您可以根據自己的要求複製並更改anon_cache_path

相關問題