Class: Rack::ICU4X::Locale

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/icu4x/locale.rb,
lib/rack/icu4x/locale/version.rb,
lib/rack/icu4x/locale/detector.rb,
lib/rack/icu4x/locale/negotiator.rb,
lib/rack/icu4x/locale/detector/query.rb,
lib/rack/icu4x/locale/detector/cookie.rb,
lib/rack/icu4x/locale/detector/header.rb

Overview

Rack middleware that detects user’s preferred locales from various sources.

Uses ICU4X’s maximize for script-safe language negotiation that respects script boundaries (e.g., zh-TW/Hant will NOT match zh-CN/Hans).

Examples:

Basic usage (Accept-Language header only)

use Rack::ICU4X::Locale, locales: %w[en ja]

With multiple detectors

use Rack::ICU4X::Locale,
  locales: %w[en ja],
  detectors: [{ query: "lang" }, { cookie: "locale" }, :header]

With custom detector

use Rack::ICU4X::Locale,
  locales: %w[en ja],
  detectors: [->(env) { env["rack.session"]&.[]("locale") }, :header]

Defined Under Namespace

Modules: Detector Classes: Error, Negotiator

Constant Summary collapse

ENV_KEY =
"rack.icu4x.locale"
DEFAULT_DETECTORS =
[:header].freeze
VERSION =
"0.6.0"

Instance Method Summary collapse

Constructor Details

#initialize(app, locales:, detectors: DEFAULT_DETECTORS, default: nil) ⇒ Locale

Returns a new instance of Locale.

Parameters:

  • app (#call)

    The Rack application

  • locales (Array<String, ICU4X::Locale>)

    List of available locales

  • detectors (Array) (defaults to: DEFAULT_DETECTORS)

    Detector specifications (optional, default: [:header])

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

    Default locale when no match is found (optional)



46
47
48
49
50
51
52
53
# File 'lib/rack/icu4x/locale.rb', line 46

def initialize(app, locales:, detectors: DEFAULT_DETECTORS, default: nil)
  @app = app
  @locales = locales.map {|locale| normalize_locale(locale) }
  @detectors = build_detectors(detectors)
  @default = default && normalize_locale(default)
  validate_default_in_locales!
  @negotiator = Negotiator.new(@locales)
end

Instance Method Details

#call(env) ⇒ Array

Returns Response from the wrapped application.

Parameters:

  • env (Hash)

    Rack environment

Returns:

  • (Array)

    Response from the wrapped application



57
58
59
60
# File 'lib/rack/icu4x/locale.rb', line 57

def call(env)
  env[ENV_KEY] = detect_locales(env)
  @app.call(env)
end