aprs.me/lib/aprsme_web/plugs/set_locale.ex
Graham McIntire 4366fa36da
Refactor conditionals to use multi-clause pattern matching
Replace case/cond/if blocks with multi-clause function dispatch
and pattern matching in function heads across 9 modules:
- WeatherUnits: case to multi-clause unit_system/1, unit_labels via do_unit_labels/1
- PacketUtils: if to pattern match on %{"id" => id}, multi-clause threshold/callsign
- SetLocale: case to multi-clause extract_locale/1
- IPGeolocation: if/cond to pattern match on conn, binary prefix matching for private_ip?
- DeviceIdentification: cond to extracted pattern_matches?/2
- MobileChannel: cond to multi-clause do_callsign_match/2
- PacketProcessor: cond to dispatch_visibility/6 on {in_bounds, has_marker} tuple
- PacketManager: destructure packet_state in heads, multi-clause maybe_cleanup/3
- AprsSymbol: case/if to multi-clause get_table_id/1, normalize_symbol_code/1
2026-02-10 17:15:49 -06:00

48 lines
1.2 KiB
Elixir

defmodule AprsmeWeb.Plugs.SetLocale do
@moduledoc """
A plug that sets the locale based on the Accept-Language header.
Falls back to English if the requested locale is not available.
"""
import Plug.Conn
def init(opts), do: opts
def call(conn, _opts) do
locale = get_locale_from_header(conn) || "en"
# Set the backend's locale for the current process
Gettext.put_locale(AprsmeWeb.Gettext, locale)
# Store locale in session for LiveView to access
conn = put_session(conn, :locale, locale)
conn
end
defp get_locale_from_header(conn) do
conn
|> get_req_header("accept-language")
|> extract_locale()
end
defp extract_locale([accept_language | _]), do: parse_accept_language(accept_language)
defp extract_locale(_), do: nil
defp parse_accept_language(accept_language) do
accept_language
|> String.split(",")
|> Enum.map(&parse_language_tag/1)
|> Enum.find(&supported_locale?/1)
end
defp parse_language_tag(tag) do
tag
|> String.trim()
|> String.split(";")
|> List.first()
|> String.split("-")
|> List.first()
|> String.downcase()
end
defp supported_locale?(locale) do
locale in ~w(en es fr de)
end
end