public
Last active

Expirable cache module for i18n gem

  • Download Gist
i18n_expirable_cache.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
module I18n
module Backend
# Expirable cache module that stores unpluralized and uninterpolated translations
module ExpirableCache
include Cache
 
protected
def fetch(*args}, &block)
locale, key, options = *args
options ||= {}
count, scope, default, separator = options.values_at(:count, :scope, :default, :separator)
separator ||= I18n.default_separator
values = options.reject { |name, value| Base::RESERVED_KEYS.include?(name) }
 
key = I18n.normalize_keys(locale, key, scope, separator)[1..-1].join(separator)
 
key = [key, pluralization_key(locale, count)].join(separator) if count
cache_store_key = cache_key(locale.to_s, key.to_s)
 
# TODO figure out how to prevent db access if value is nil
if entry = I18n.cache_store.read(cache_store_key)
entry = pluralize(locale, entry, count) if count
entry = interpolate(locale, entry, values) if values
entry
else
entry = lookup(locale, key, nil, options)
I18n.cache_store.write(cache_store_key, entry)
 
# Call the original translate method and return the translation
block[*args]
end
end
 
# TODO use built-in pluralization to support other pluralization rules
def pluralization_key(locale, count)
key = :zero if (count == 0 && pluralization_keys(locale).include?(:zero))
key ||= count == 1 ? :one : :other
end
 
def pluralization_keys(locale)
@pluralization_keys ||= {}
@pluralization_keys[locale] ||= I18n.t('i18n.plural.keys', :locale => locale)
end
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.