@@ -763,6 +763,19 @@ defmodule Gettext do
763763 Gettext.get_locale(MyApp.Gettext)
764764 #=> "pt_BR"
765765
766+ The current process's locale will change even if the passed `locale` is not
767+ supported. If you think this can cause an issue consider using `known_locales/1`
768+ to handle unsupported locales.
769+
770+ ## Example
771+
772+ # Handle unsupported locales based on your requirements
773+ defp handle_locale(locale, true, backend), do: {:ok, Process.put(backend, locale)}
774+ defp handle_locale(_locale, false, backend), do: {:error, :unsupported_locale}
775+
776+ # In your main function
777+ is_in_allowed_locale = locale in known_locales(backend)
778+ handle_locale(locale, is_in_allowed_locale, backend)
766779 """
767780 @ doc section: :locale
768781 @ spec put_locale ( backend , locale ) :: locale | nil
@@ -771,6 +784,17 @@ defmodule Gettext do
771784 def put_locale ( _backend , locale ) ,
772785 do: raise ( ArgumentError , "put_locale/2 only accepts binary locales, got: #{ inspect ( locale ) } " )
773786
787+ @ doc """
788+ Similar to `put_locale/2`, but it raises an error if the passed locale doesn't exist in the known_locales.
789+ """
790+ @ doc section: :locale
791+ @ spec put_locale! ( backend , locale ) :: locale | nil
792+ def put_locale! ( backend , locale ) when is_binary ( locale ) ,
793+ do: put_locale_with_fallback ( backend , locale )
794+
795+ def put_locale! ( _backend , locale ) ,
796+ do: raise ( ArgumentError , "put_locale/2 only accepts binary locales, got: #{ inspect ( locale ) } " )
797+
774798 @ doc """
775799 Returns the message of the given string with a given context in the given domain.
776800
@@ -1154,4 +1178,18 @@ defmodule Gettext do
11541178
11551179 defp domain_or_default ( backend , :default ) , do: backend . __gettext__ ( :default_domain )
11561180 defp domain_or_default ( _backend , domain ) when is_binary ( domain ) , do: domain
1181+
1182+ @ spec put_locale_with_fallback ( backend , locale ) :: binary ( ) | nil
1183+ defp put_locale_with_fallback ( backend , locale ) do
1184+ allowed_locales = known_locales ( backend )
1185+ is_allowed_locale = locale in allowed_locales
1186+
1187+ case is_allowed_locale do
1188+ true ->
1189+ put_locale ( backend , locale )
1190+
1191+ false ->
1192+ raise ( ArgumentError , "put_locale!/2 only support known locales, got: #{ inspect ( locale ) } " )
1193+ end
1194+ end
11571195end
0 commit comments