How can the cache for the views with translations

2019-04-02 17:48发布

Imagine you have two views with code like the following:

controller_a/a.html.erb

  <%= content_tag(:div) do %>
     <%= I18n.t "some.key" %>
  <% end %>

controller_b/b.html.erb

  <%= content_tag(:div) do %>
     <%= I18n.t "some.key" %>
  <% end %>

  <%= content_tag(:div) do %>
     <%= I18n.t "some.other_key" %>
  <% end %>

So, a.html.erb is on controller_a#a, while b.html.erb is on controller_b#b. Both actions are cached by caches_action. How can I make sure that when I change the some.key translation key, both views are invalidated? How could I build a generic mechanism?

1条回答
Explosion°爆炸
2楼-- · 2019-04-02 18:12

Say, in your ApplicationController create the following class-method (or in a lib and extend by it):

def self.i18n_digest(*scopes)
    Digest::MD5.hexdigest I18n.t(scopes).to_s
end

Then you can use :cache_path option in your caches_action this way:

caches_action :some_action, cache_path: { some_key: i18n_digest('some', 'foo') }

Just make sure that you set the locale in a before_filter before this statement.

Docs on cache_path.

Note: I'm using the scope of translation ('some') to get all its nested messages as a hash.

查看更多
登录 后发表回答