Class: I18n::Backend::LocaleExtractor

  • Object
show all
Defined in:


Backend that lazy loads translations based on the current locale. This implementation avoids loading all translations up front. Instead, it only loads the translations that belong to the current locale. This offers a performance incentive in local development and test environments for applications with many translations for many different locales. It’s particularly useful when the application only refers to a single locales’ translations at a time (ex. A Rails workload). The implementation identifies which translation files from the load path belong to the current locale by pattern matching against their path name.

Specifically, a translation file is considered to belong to a locale if: a) the filename is in the I18n load path b) the filename ends in a supported extension (ie. .yml, .json, .po, .rb) c) the filename starts with the locale identifier d) the locale identifier and optional proceeding text is separated by an underscore, ie. “_”.

Examples: Valid files that will be selected by this backend:

“files/locales/en_translation.yml” (Selected for locale “en”) “files/locales/fr.po” (Selected for locale “fr”)

Invalid files that won’t be selected by this backend:

“files/locales/translation-file” “files/locales/en-translation.unsupported” “files/locales/french/translation.yml” “files/locales/fr/translation.yml”

The implementation uses this assumption to defer the loading of translation files until the current locale actually requires them.

The backend has two working modes: lazy_load and eager_load.

Note: This backend should only be enabled in test environments! When the mode is set to false, the backend behaves exactly like the Simple backend, with an additional check that the paths being loaded abide by the format. If paths can’t be matched to the format, an error is raised.

You can configure lazy loaded backends through the initializer or backends accessor:

# In test environments

I18n.backend = true)

# In other environments, such as production and CI

I18n.backend = false) # default

Class Method Summary collapse

Class Method Details

.locale_from_path(path) ⇒ Object

# File 'lib/i18n/backend/lazy_loadable.rb', line 57

def locale_from_path(path)
  name = File.basename(path, ".*")
  locale = name.split("_").first
  locale.to_sym unless locale.nil?