【发布时间】:2011-12-12 10:52:37
【问题描述】:
在我的 Rails 3.1.2 项目中,我使用 ActiveRecord 作为 I18n.backend。我想在 MemCache 中缓存值。但是我的开发环境和测试环境之间存在奇怪的行为差异。
我的'config/initializers/i18n.rb'
# https://github.com/svenfuchs/i18n-active_record/blob/master/lib/i18n/backend/active_record/translation.rb
require 'i18n/backend/active_record'
require 'i18n_cache_backend'
I18n.default_locale = :en
I18n.backend.class.send(:include, I18n::Backend::Fallbacks)
active_record_backend = I18n::Backend::ActiveRecord.new
active_record_backend.class.send(:include, I18n::Backend::Fallbacks)
I18n::Backend::ActiveRecord.send :include, I18n::Backend::Cache
I18n.cache_store = Rails.application.config.i18n_cache_store
I18n.backend = I18n::Backend::Chain.new(active_record_backend, I18n.backend)
我的 'lib/i18n_cache_backend',覆盖 :store_translation 方法来清理缓存。
module I18n::Backend::Cache
def store_translations(locale, data, options = {})
flatten_keys(data, true) do |key, value|
c_key = cache_key(locale, key.to_s, options)
I18n.cache_store.delete c_key
end
super
end
end
在 'config/environments/development.rb' 我有:
config.i18n_cache_store = ActiveSupport::Cache.lookup_store(:mem_cache_store,
'localhost', :namespace => "development")
在 'config/environments/beta.rb' 我有:
config.i18n_cache_store = ActiveSupport::Cache.lookup_store(:mem_cache_store,
'memcache.v.l', :namespace => "beta")
在开发 Rails 控制台中:
ruby-1.8.7-p352 :008 > I18n.cache_store.clear
=> [<MemCache::Server: localhost:11211 [1] (CONNECTED)>]
ruby-1.8.7-p352 :009 > helper.t 'main.wire'
[SQL QUERY GOES HERE]
=> "Wire"
ruby-1.8.7-p352 :010 > helper.t 'main.wire'
=> "Wire"
ruby-1.8.7-p352 :011 > I18n.backend.store_translations(:en, {:main => {:wire => "foo bar baz"}}, {:rescue_format=>:html})
[SQL UPDATES GOES HERE]
=> {:"main.wire"=>"foo bar baz"}
ruby-1.8.7-p352 :012 > helper.t 'main.wire'
[SQL QUERY GOES HERE]
=> "foo bar baz"
ruby-1.8.7-p352 :013 > helper.t 'main.wire'
=> "foo bar baz"
在 beta env rails 控制台中:
ruby-1.8.7-p352 :001 > I18n.cache_store.clear
=> [<MemCache::Server: memcache.v.l:11211 [1] (CONNECTED)>]
ruby-1.8.7-p352 :002 > helper.t 'main.wire'
[SQL QUERY GOES HERE]
=> "Wire"
ruby-1.8.7-p352 :003 > helper.t 'main.wire'
=> "Wire"
ruby-1.8.7-p352 :004 > I18n.backend.store_translations(:en, {:main => {:wire => "foo bar baz"}}, {:rescue_format=>:html})
[SQL UPDATES GOES HERE]
=> {:"main.wire"=>"foo bar baz"}
ruby-1.8.7-p352 :005 > helper.t 'main.wire'
=> "Wire"
ruby-1.8.7-p352 :006 > helper.t 'main.wire'
=> "Wire"
ruby-1.8.7-p352 :007 > I18n.cache_store.clear
=> [<MemCache::Server: memcache.v.l:11211 [1] (CONNECTED)>]
ruby-1.8.7-p352 :008 > helper.t 'main.wire'
[SQL QUERY GOES HERE]
=> "foo bar baz"
ruby-1.8.7-p352 :009 > helper.t 'main.wire'
=> "foo bar baz"
有人有想法吗?在每个 :store_translation 之后,用于翻译的开发缓存都被清除,在 beta 中,除非我执行 I18n.cache_store.clear,否则不会刷新缓存值
【问题讨论】:
标签: ruby-on-rails internationalization memcached