From 22a54adc8a374bc660eb6c10f05729a407c133c8 Mon Sep 17 00:00:00 2001 From: Simon Hansen Date: Sun, 7 Jul 2024 12:46:41 +0200 Subject: [PATCH] Translator.translate/2 should fall back to default locale when translation is missing (#84) --- lib/trans/translator.ex | 6 +++++- test/trans/translator_test.exs | 6 ++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/trans/translator.ex b/lib/trans/translator.ex index c492834..86818ad 100644 --- a/lib/trans/translator.ex +++ b/lib/trans/translator.ex @@ -182,7 +182,7 @@ defmodule Trans.Translator do end end - defp translate_fields(%{__struct__: module} = struct, locale, default_locale) do + defp translate_fields(%{__struct__: module} = struct, locale, default_locale) when is_list(locale) do fields = module.__trans__(:fields) Enum.reduce(fields, struct, fn field, struct -> @@ -193,6 +193,10 @@ defmodule Trans.Translator do end) end + defp translate_fields(%{__struct__: module} = struct, locale, default_locale) do + translate_fields(struct, [locale], default_locale) + end + defp translate_assocs(%{__struct__: module} = struct, locale) do associations = module.__schema__(:associations) embeds = module.__schema__(:embeds) diff --git a/test/trans/translator_test.exs b/test/trans/translator_test.exs index c79af82..6e61851 100644 --- a/test/trans/translator_test.exs +++ b/test/trans/translator_test.exs @@ -44,6 +44,12 @@ defmodule Trans.TranslatorTest do assert translated.content == struct.content end + + test "falls back to the default locale if translation does not exist", %{struct: struct} do + translated = Translator.translate(struct, :fr) + + assert translated.content == struct.content + end end describe inspect(&Translator.translate/3) do