Skip to content

Feature Suggestion: Respect fallbacks #732

@mingan

Description

@mingan

Description

1️⃣ The built-in embed_fallback_translations plugin does not handle fallback configuration available through I18n.fallbacks. It always goes straight to the default locale. Admittedly, it's documented in the readme but still a bit surprising.

2️⃣ A custom plugin has to be registered which is not documented.

Describe the solution

I ended up writing a custom plugin which combines translation data for each locale with all its fallbacks in sequence. I'm not sure whether it should replace the existing plugin, be an official alternative or a separate gem.

Custom plugin code
# frozen_string_literal: true

require 'i18n-js/embed_fallback_translations_plugin'

module I18nJS
  class EmbedFallbackTranslationsConfigurablePlugin < I18nJS::EmbedFallbackTranslationsPlugin

    def transform(translations:)
      return translations unless enabled?

      default_locale = I18n.default_locale.to_sym
      fallbacks = I18n.fallbacks.to_h do |locale, fallbacks|
        [locale.to_sym, fallbacks.uniq - [locale.to_sym]]
      end

      translations_with_fallback = {}
      fallbacks.each_key do |locale|
        translations_with_fallback[locale] = translations[locale] || {}
      end

      fallbacks.each do |locale, fallback_locales|
        next if locale == default_locale

        fallback_locales.each do |fallback_locale|
          next if locale == fallback_locale

          translations_with_fallback[locale] = Utils.deep_merge(
            translations[fallback_locale], translations_with_fallback[locale]
          )
        end
      end

      translations_with_fallback
    end
  end

  I18nJS.register_plugin(EmbedFallbackTranslationsConfigurablePlugin)
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions