Class: Rack::LocaleRootRedirect

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/locale_root_redirect/version.rb,
lib/rack/locale_root_redirect/middleware.rb

Constant Summary collapse

VERSION =
'0.3'

Instance Method Summary collapse

Constructor Details

#initialize(app, locales = {}) ⇒ LocaleRootRedirect

Returns a new instance of LocaleRootRedirect.



5
6
7
8
9
10
# File 'lib/rack/locale_root_redirect/middleware.rb', line 5

def initialize(app, locales = {})
  @locales = locales
  @available_locales = locales.keys.map(&:to_s)
  @default_locale = @available_locales.first
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rack/locale_root_redirect/middleware.rb', line 12

def call(env)
  status, headers, response = @app.call(env)

  if root_request?(env)
    language_matcher = env['rack-accept.request'].language.tap { |m| m.first_level_match = true }
    redirect_lang = language_matcher.best_of(@available_locales) || @default_locale

    status = 302
    query_string = env['QUERY_STRING'] == '' ? '' : "?#{env['QUERY_STRING']}"
    headers['Location'] = @locales[redirect_lang.to_sym] + query_string
  end

  [status, headers, response]
end