Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature Suggestion: Respect fallbacks #732

Open
mingan opened this issue Jan 17, 2025 · 0 comments
Open

Feature Suggestion: Respect fallbacks #732

mingan opened this issue Jan 17, 2025 · 0 comments

Comments

@mingan
Copy link

mingan commented Jan 17, 2025

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant