Parses HTTP Accept-Language headers and finds the best matching locale.
The Accept-Language header is parsed per RFC 2616 into quality-tagged language tags which are then matched against the supported locales. The primary entry point is best_match/1 which returns the highest-quality tag that matches a supported locale.
Summary
Functions
Returns the best matching locale for the given Accept-Language header.
Parses an Accept-Language header and validates each language tag
against known locales.
Tokenizes an Accept-Language header string into a list of
{quality, language_tag_string} tuples sorted by quality descending.
Functions
@spec best_match(term()) :: {:ok, Localize.LanguageTag.t()} | {:error, Exception.t()}
Returns the best matching locale for the given Accept-Language header.
Parses the header and returns the highest-quality language tag that
matches a supported locale. A tag that only resolves to a supported
locale by fallback, such as ja when no Japanese locale is supported,
is skipped in favour of the next tag in the header.
Arguments
headeris an Accept-Language header string.
Returns
{:ok, Localize.LanguageTag.t()}or{:error, exception}: aLocalize.UnknownLocaleErrorwhen no tag matches a supported locale, or aLocalize.InvalidValueErrorwhenheaderis not a string.
Examples
iex> {:ok, locale} = Localize.AcceptLanguage.best_match("en-US,fr;q=0.8")
iex> locale.language
"en"
@spec parse(term()) :: {:ok, [{float(), {:ok, Localize.LanguageTag.t()} | {:error, term()}}]} | {:error, Exception.t()}
Parses an Accept-Language header and validates each language tag
against known locales.
Arguments
headeris an Accept-Language header string.
Returns
{:ok, [{quality, result}]}whereresultis either{:ok, Localize.LanguageTag.t()}or{:error, reason}, or{:error, exception}whenheaderis not a string.
Examples
iex> {:ok, results} = Localize.AcceptLanguage.parse("en-US,zh;q=0.8")
iex> length(results)
2
Tokenizes an Accept-Language header string into a list of
{quality, language_tag_string} tuples sorted by quality descending.
Arguments
headeris an Accept-Language header string.
Returns
- A list of
{quality, language_tag_string}tuples. Aheaderthat is not a string has no tags.
Examples
iex> Localize.AcceptLanguage.tokenize("en-US,en;q=0.9,fr;q=0.8")
[{1.0, "en-us"}, {0.9, "en"}, {0.8, "fr"}]