Created
April 9, 2010 20:32
-
-
Save szimek/361559 to your computer and use it in GitHub Desktop.
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
# Based on I18n::Backend::ActiveRecord::Missing, but provides some additional features: | |
# - creates Translation object for each locale defined in I18n.available_locales | |
# - looks up the translation using Simple backend and sets it as Translation#value | |
# | |
# Important! Remember to provide i18n.plural.keys in your YAML files. For example: | |
# | |
# # en.yml | |
# en: | |
# i18n: | |
# plural: | |
# keys: [:zero, :one, :other] | |
# | |
# # pl.yml | |
# pl: | |
# i18n: | |
# plural: | |
# keys: [:zero, :one, :few, :other] | |
module I18n | |
module Backend | |
class ActiveRecord | |
module MissingWithFallback | |
def fallback_backend | |
@fallback_backend ||= I18n::Backend::Simple.new | |
end | |
def store_default_translations(locale, key, options = {}) | |
count, scope, default, separator = options.values_at(:count, *Base::RESERVED_KEYS) | |
separator ||= I18n.default_separator | |
keys = I18n.normalize_keys(locale, key, scope, separator)[1..-1] | |
key = keys.join(separator || I18n.default_separator) | |
unless ActiveRecord::Translation.locale(locale).lookup(key, separator).exists? | |
interpolations = options.reject { |name, value| Base::RESERVED_KEYS.include?(name) }.keys | |
keys = count ? I18n.t('i18n.plural.keys', :locale => locale).map { |k| [key, k].join(separator) } : [key] | |
keys.each do |key| | |
I18n.available_locales.each do |available_locale| | |
store_default_translation(available_locale, key, interpolations) | |
end | |
end | |
end | |
end | |
def store_default_translation(locale, key, interpolations) | |
translation = ActiveRecord::Translation.new :locale => locale.to_s, :key => key | |
translation.interpolations = interpolations | |
translation.value = fallback_backend.send(:lookup, locale, key) | |
translation.save | |
end | |
def translate(locale, key, options = {}) | |
super | |
rescue I18n::MissingTranslationData => e | |
self.store_default_translations(locale, key, options) | |
raise e | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment