Module: Philiprehberger::LocaleKit

Defined in:
lib/philiprehberger/locale_kit.rb,
lib/philiprehberger/locale_kit/data.rb,
lib/philiprehberger/locale_kit/locale.rb,
lib/philiprehberger/locale_kit/version.rb,
lib/philiprehberger/locale_kit/negotiator.rb,
lib/philiprehberger/locale_kit/accept_language.rb

Defined Under Namespace

Modules: AcceptLanguage, Data, Negotiator Classes: Error, Locale

Constant Summary collapse

VERSION =
'0.3.0'

Class Method Summary collapse

Class Method Details

.languagesHash<String, String>

Returns a hash of common ISO 639-1 language codes to English names.

Returns:

  • (Hash<String, String>)

    language code to name mapping



69
70
71
# File 'lib/philiprehberger/locale_kit.rb', line 69

def self.languages
  Data::LANGUAGES
end

.negotiate(requested, available, default: nil) ⇒ Locale?

Negotiates the best matching locale from available options.

Parameters:

  • requested (Array<String, Locale>)

    locales requested by the client

  • available (Array<String, Locale>)

    locales the server supports

  • default (String, Locale, nil) (defaults to: nil)

    fallback locale if no match is found

Returns:

  • (Locale, nil)

    the best match, the default, or nil



54
55
56
# File 'lib/philiprehberger/locale_kit.rb', line 54

def self.negotiate(requested, available, default: nil)
  Negotiator.negotiate(requested, available, default: default)
end

.parse(tag) ⇒ Locale

Parses a BCP 47 language tag string into a Locale object.

Parameters:

  • tag (String)

    a BCP 47 language tag (e.g., “en-US”, “zh-Hant-TW”)

Returns:

  • (Locale)

    the parsed locale

Raises:

  • (ArgumentError)

    if the tag is not a valid BCP 47 tag



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/philiprehberger/locale_kit.rb', line 31

def self.parse(tag)
  raise ArgumentError, "tag must be a String, got: #{tag.class}" unless tag.is_a?(String)

  match = TAG_PATTERN.match(tag.strip)
  raise ArgumentError, "invalid BCP 47 tag: #{tag.inspect}" unless match

  extensions = parse_extensions(match[:extensions])

  Locale.new(
    match[:language],
    script: match[:script],
    region: match[:region],
    variant: match[:variant],
    extensions: extensions
  )
end

.parse_accept_language(header) ⇒ Array<Hash>

Parses an HTTP Accept-Language header into locale/quality pairs.

Parameters:

  • header (String)

    the Accept-Language header value

Returns:

  • (Array<Hash>)

    sorted array of { locale:, quality: } hashes



62
63
64
# File 'lib/philiprehberger/locale_kit.rb', line 62

def self.parse_accept_language(header)
  AcceptLanguage.parse(header)
end

.regionsHash<String, String>

Returns a hash of common ISO 3166-1 alpha-2 region codes to English names.

Returns:

  • (Hash<String, String>)

    region code to name mapping



76
77
78
# File 'lib/philiprehberger/locale_kit.rb', line 76

def self.regions
  Data::REGIONS
end