class Rack::LocaleRootRedirect

Constants

RACK_ACCEPT_MISSING
REDIRECTED_RESPONSE_REGEX
ROOT_REQUEST_REGEX
STATUS
VERSION

Public Class Methods

new(app, locales = {}) click to toggle source

@private

# File lib/rack/locale_root_redirect/middleware.rb, line 9
def initialize(app, locales = {})
  @locales = locales
  @available_locales = locales.keys.map(&:to_s)
  @default_locale = @available_locales.first

  @app = app
end

Public Instance Methods

call(env) click to toggle source

@private

# File lib/rack/locale_root_redirect/middleware.rb, line 18
def call(env)
  status, headers, response = @app.call(env)

  if should_redirect?(env, status)
    locale = best_locale(env)

    status = STATUS
    query_string = env['QUERY_STRING'] == '' ? '' : "?#{env['QUERY_STRING']}"
    headers['Vary'] = 'Accept-Language'
    headers['Location'] = @locales[locale.to_sym] + query_string
  end

  [status, headers, response]
end

Protected Instance Methods

best_locale(env) click to toggle source

Return the best locale to redirect to based on the request enviroment

# File lib/rack/locale_root_redirect/middleware.rb, line 51
def best_locale(env)
  if accept = env['rack-accept.request']
    matcher = accept.language.tap { |m| m.first_level_match = true }
    matcher.best_of(@available_locales) || @default_locale
  else
    raise StandardError, RACK_ACCEPT_MISSING
  end
end
redirected_response?(status) click to toggle source

Return whether the response we’re altering is already a redirection

# File lib/rack/locale_root_redirect/middleware.rb, line 46
def redirected_response?(status)
  REDIRECTED_RESPONSE_REGEX.match(status.to_s)
end
root_request?(env) click to toggle source

Return whether the request was on the root endpoint (‘/`)

# File lib/rack/locale_root_redirect/middleware.rb, line 41
def root_request?(env)
  ROOT_REQUEST_REGEX.match(env['PATH_INFO'])
end
should_redirect?(env, status) click to toggle source

Return whether we must act on this request

# File lib/rack/locale_root_redirect/middleware.rb, line 36
def should_redirect?(env, status)
  !redirected_response?(status) && root_request?(env)
end