Skip to content
This repository
Newer
Older
100644 42 lines (34 sloc) 0.963 kb
01c36960 » josh
2008-12-07 Add experimental I18n Locale middleware
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
ccb8b09d » jamesarosen
2012-08-18 Rack::Locale: reset I18n.locale even if exception
11
12 begin
13 locale = accept_locale(env) || I18n.default_locale
14 locale = env['rack.locale'] = I18n.locale = locale.to_s
15 status, headers, body = @app.call(env)
16 headers['Content-Language'] = locale
17 [status, headers, body]
18 ensure
19 I18n.locale = old_locale
20 end
01c36960 » josh
2008-12-07 Add experimental I18n Locale middleware
21 end
0c1a7ac1 » jamesarosen
2012-08-18 Rack::Locale: extract helper method
22
23 private
24
25 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
26 def accept_locale(env)
27 accept_langs = env["HTTP_ACCEPT_LANGUAGE"]
28 return if accept_langs.nil?
29
30 languages_and_qvalues = accept_langs.split(",").map { |l|
31 l += ';q=1.0' unless l =~ /;q=\d+(?:\.\d+)?$/
32 l.split(';q=')
33 }
34
35 lang = languages_and_qvalues.sort_by { |(locale, qvalue)|
36 qvalue.to_f
be2193bd » jamesarosen
2012-08-18 Rack::Locale: support "*" langague
37 }.last.first
0c1a7ac1 » jamesarosen
2012-08-18 Rack::Locale: extract helper method
38
be2193bd » jamesarosen
2012-08-18 Rack::Locale: support "*" langague
39 lang == '*' ? nil : lang
0c1a7ac1 » jamesarosen
2012-08-18 Rack::Locale: extract helper method
40 end
01c36960 » josh
2008-12-07 Add experimental I18n Locale middleware
41 end
42 end
Something went wrong with that request. Please try again.