Created
April 5, 2010 14:17
-
-
Save szimek/356383 to your computer and use it in GitHub Desktop.
Expirable cache module for i18n gem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment