Changeset View
Changeset View
Standalone View
Standalone View
lib/kolab_chat/locale.ex
- This file was added.
defmodule KolabChat.Locale do | |||||
import Plug.Conn | |||||
def init(opts), do: opts | |||||
def call(conn, _opts) do | |||||
case get_session(conn, :locale) || client_locale(conn) do | |||||
nil -> | |||||
conn | |||||
locale -> | |||||
Gettext.put_locale(KolabChat.Gettext, locale) | |||||
put_session(conn, :locale, locale) | |||||
end | |||||
end | |||||
# Gets supported locale code from the client | |||||
# Uses 'locale' parameter or Accept-Language header | |||||
defp client_locale(conn) do | |||||
supported = Gettext.known_locales(KolabChat.Gettext) | |||||
locale = conn.params["locale"] || get_req_header(conn, "accept-language") | |||||
locale | |||||
|> to_string() | |||||
|> String.split(",") | |||||
|> Enum.map(&parse_locale/1) | |||||
|> Enum.filter(fn(x) -> Enum.member?(supported, x) end) | |||||
|> Enum.at(0) | |||||
end | |||||
# Extracts locale code from an element of Accept-Language header | |||||
defp parse_locale(locale) do | |||||
locale | |||||
|> String.split(";") | |||||
|> Enum.at(0) | |||||
|> String.trim() | |||||
|> String.replace("-", "_") | |||||
end | |||||
end |