2020-01-26 20:36:50 +00:00
|
|
|
defmodule Mobilizon.Web.Gettext do
|
2017-12-08 08:58:14 +00:00
|
|
|
@moduledoc """
|
|
|
|
A module providing Internationalization with a gettext-based API.
|
|
|
|
|
|
|
|
By using [Gettext](https://hexdocs.pm/gettext),
|
|
|
|
your module gains a set of macros for translations, for example:
|
|
|
|
|
2020-01-26 20:36:50 +00:00
|
|
|
import Mobilizon.Web.Gettext
|
2017-12-08 08:58:14 +00:00
|
|
|
|
|
|
|
# Simple translation
|
|
|
|
gettext "Here is the string to translate"
|
|
|
|
|
|
|
|
# Plural translation
|
|
|
|
ngettext "Here is the string to translate",
|
|
|
|
"Here are the strings to translate",
|
|
|
|
3
|
|
|
|
|
|
|
|
# Domain-based translation
|
|
|
|
dgettext "errors", "Here is the error message to translate"
|
|
|
|
|
|
|
|
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
|
|
|
|
"""
|
2018-10-11 15:37:39 +00:00
|
|
|
use Gettext, otp_app: :mobilizon
|
2019-10-01 11:08:09 +00:00
|
|
|
|
|
|
|
def put_locale(locale) do
|
|
|
|
locale = determine_best_locale(locale)
|
2020-01-26 20:36:50 +00:00
|
|
|
Gettext.put_locale(Mobilizon.Web.Gettext, locale)
|
2019-10-01 11:08:09 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
@spec determine_best_locale(String.t()) :: String.t()
|
|
|
|
def determine_best_locale(locale) do
|
|
|
|
locale = String.trim(locale)
|
2020-01-26 20:36:50 +00:00
|
|
|
locales = Gettext.known_locales(Mobilizon.Web.Gettext)
|
2019-10-01 11:08:09 +00:00
|
|
|
|
|
|
|
cond do
|
|
|
|
# Either it matches directly, eg: "en" => "en", "fr" => "fr", "fr_FR" => "fr_FR"
|
|
|
|
locale in locales -> locale
|
|
|
|
# Either the first part matches, "fr_CA" => "fr"
|
|
|
|
split_locale(locale) in locales -> split_locale(locale)
|
|
|
|
# Otherwise default to english
|
|
|
|
true -> "en"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
# Keep only the first part of the locale
|
|
|
|
defp split_locale(locale), do: locale |> String.split("_", trim: true, parts: 2) |> hd
|
2017-12-08 08:58:14 +00:00
|
|
|
end
|