Skip to content
Newer
Older
100644 39 lines (31 sloc) 915 Bytes
01c3696 @josh Add experimental I18n Locale middleware
josh authored Dec 7, 2008
1 require 'i18n'
2
3 module Rack
4 class Locale
5 def initialize(app)
6 @app = app
7 end
8
9 def call(env)
10 old_locale = I18n.locale
0c1a7ac Rack::Locale: extract helper method
James A. Rosen authored Aug 18, 2012
11 locale = accept_locale(env) || I18n.default_locale
01c3696 @josh Add experimental I18n Locale middleware
josh authored Dec 7, 2008
12 locale = env['rack.locale'] = I18n.locale = locale.to_s
13 status, headers, body = @app.call(env)
14 headers['Content-Language'] = locale
15 I18n.locale = old_locale
16 [status, headers, body]
17 end
0c1a7ac Rack::Locale: extract helper method
James A. Rosen authored Aug 19, 2012
18
19 private
20
21 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
22 def accept_locale(env)
23 accept_langs = env["HTTP_ACCEPT_LANGUAGE"]
24 return if accept_langs.nil?
25
26 languages_and_qvalues = accept_langs.split(",").map { |l|
27 l += ';q=1.0' unless l =~ /;q=\d+(?:\.\d+)?$/
28 l.split(';q=')
29 }
30
31 lang = languages_and_qvalues.sort_by { |(locale, qvalue)|
32 qvalue.to_f
be2193b Rack::Locale: support "*" langague
James A. Rosen authored Aug 18, 2012
33 }.last.first
0c1a7ac Rack::Locale: extract helper method
James A. Rosen authored Aug 19, 2012
34
be2193b Rack::Locale: support "*" langague
James A. Rosen authored Aug 19, 2012
35 lang == '*' ? nil : lang
0c1a7ac Rack::Locale: extract helper method
James A. Rosen authored Aug 19, 2012
36 end
01c3696 @josh Add experimental I18n Locale middleware
josh authored Dec 7, 2008
37 end
38 end
Something went wrong with that request. Please try again.