1
我有兩個基本呈現相同頁面的網址。根據location.href
,輕微的差異可以通過JavaScript輕鬆執行。無論如何,即使路線指向相同的controller#action
,第二條路線也不會使用前者緩存的頁面。我怎樣才能做到這一點?如何在rails中爲不同的url使用相同的緩存頁面?
我有兩個基本呈現相同頁面的網址。根據location.href
,輕微的差異可以通過JavaScript輕鬆執行。無論如何,即使路線指向相同的controller#action
,第二條路線也不會使用前者緩存的頁面。我怎樣才能做到這一點?如何在rails中爲不同的url使用相同的緩存頁面?
我在我的網站上有一個有趣的需求 - 對不同的主題,不同的頁面可以從同一個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
。