Ruby on rails 3 如何对rails中的不同URL使用相同的缓存页面?
我有两个基本上呈现相同页面的URL。根据Ruby on rails 3 如何对rails中的不同URL使用相同的缓存页面?,ruby-on-rails-3,caching,Ruby On Rails 3,Caching,我有两个基本上呈现相同页面的URL。根据location.href,可以通过javascript轻松执行这些细微的差异。无论如何,即使路由指向相同的控制器#action,第二个路由也不会使用前者缓存的页面。我怎样才能做到这一点呢?我在你对面的网站上有一个有趣的要求——由于主题不同,可以从同一个url返回不同的页面。因此,我提出了一个名为“匿名缓存”的解决方案,我制作了自己的缓存密钥,包括额外的参数。但我认为这个解决方案可以给你一些线索 module AnonymousCache def se
location.href
,可以通过javascript轻松执行这些细微的差异。无论如何,即使路由指向相同的控制器#action
,第二个路由也不会使用前者缓存的页面。我怎样才能做到这一点呢?我在你对面的网站上有一个有趣的要求——由于主题不同,可以从同一个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\u cache\u path
方法是我为页面缓存创建规范键的地方。您可以看到我在其中包含了当前主题
您可以复制此文件并根据需要更改非缓存路径