Rails Rails 如何根据多国语言 cache 页面?

linjunhalida · 2011年11月30日 · 最后由 huacnlee 回复于 2016年11月09日 · 4015 次阅读

hello, rails 自带的几个 cache 功能,cache_page 和 cache_action 不能根据语言或者参数来设置,

cache fragment 倒是可以把语言加进去,但是 expire 需要用 regexp 来全部 expire, 大家是如何做的呢?

主要是 cache_action 不好搞...

试试用 cache_path

class HomeController < ApplicationController
  caches_action :index, :cache_path =>  Proc.new { |c| "home/index" }
end

#1 楼 @linjunhalida@huacnlee 所述,用 cache_path 来指定 param。

Bonus: cache_action 可以把 layout 滤掉。

caches_action :index, :cache_path => Proc.new { |c| "home/index" } 不过这个是跟 model 的,我要根据用户的 locale 参数来选 cache... 我找找源码看看。

caches_action :index, :cache_path => Proc.new {|c| "home/index-#{I18n.locale.to_s}"}

酷!看了 action.rb 里面的文档,搞定了哈!

#5 楼 @linjunhalida 其实或许该像个办法抽象出来,不然那个地方你忘记加 I18n.locale.to_s 的时候就悲剧了

只是 1,2 个页面,就这样啦,只是一行代码的事情何必抽象呢。如果有再多的话考虑如何做。

为支持 Fragment caching 需要覆盖 cache helper:

module ApplicationHelper
  # Override cache helper for support multiple I18n locale
  def cache(name = {}, options = {}, &block)
    options ||= {}
    super([I18n.locale, name], options, &block)
  end
end
需要 登录 后方可回复, 如果你还没有账号请 注册新账号