This repository has been archived by the owner on Dec 12, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 87
Exception handler using Translates storage class
weibel edited this page Sep 13, 2010
·
1 revision
We have loads of small texts in one of our applications so maintaining the default_locale yml became labor intensive. Hence I wrote this short fragment and put it in lib/.
It will rescue the MissingTranslationData exception and look up the default_locale. If a translation is nonexistent it will insert a proper key:value pair in the default_locale yml using Translates storage class. The missing translation will then be visible in the Translate GUI.
def exception_handler(exception, locale, key, options) if I18n::MissingTranslationData === exception if locale == I18n.default_locale # The translation has failed being looked up in the default_locale yml. # This happens whenever translated strings have been added in the application without # adding a corresponding key:value pair in the default_locale yml # The following lines uses the Translate plugins functionality to create the missing # key:value pairs for default_locale and store the yaml I18n.backend.store_translations(I18n.default_locale, get_i18n_hash(options[:scope], key)) Translate::Storage.new(I18n.default_locale).write_to_file I18n.backend.send(:init_translations) return key else # Translation has not yet been added to the chosen locale. Look up default_locale return I18n.t key, :locale => I18n.default_locale, :scope => options[:scope] end else raise exception end end # Convert something like: # # get_i18n_hash([:controllers, :profile], "Releases") # # to: # # { # :controllers => { # :profile => { # "Releases" => "Releases" # } # } # } def get_i18n_hash(scope, value) res = {value => value} return res if scope.nil? scope = [scope] if !scope.is_a? Array res = scope.reverse.inject({value => value}) { |result, key| {key => result} } res end I18n.exception_handler = :exception_handler