Localize.AcceptLanguage (Localize Web v1.3.0)

Copy Markdown View Source

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

best_match(header)

@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

  • header is an Accept-Language header string.

Returns

Examples

iex> {:ok, locale} = Localize.AcceptLanguage.best_match("en-US,fr;q=0.8")
iex> locale.language
"en"

parse(header)

@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

  • header is an Accept-Language header string.

Returns

  • {:ok, [{quality, result}]} where result is either {:ok, Localize.LanguageTag.t()} or {:error, reason}, or

  • {:error, exception} when header is not a string.

Examples

iex> {:ok, results} = Localize.AcceptLanguage.parse("en-US,zh;q=0.8")
iex> length(results)
2

tokenize(header)

@spec tokenize(term()) :: [{float(), String.t()}]

Tokenizes an Accept-Language header string into a list of {quality, language_tag_string} tuples sorted by quality descending.

Arguments

  • header is an Accept-Language header string.

Returns

  • A list of {quality, language_tag_string} tuples. A header that 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"}]