Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # inspired by: https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/locale.rb
- class LocaleMiddleware
- def initialize(app)
- @app = app
- end
- def call(env)
- old_locale = I18n.locale
- begin
- locale = accept_locale(env) || I18n.default_locale
- env['rack.locale'] = I18n.locale = locale.to_s
- status, headers, body = @app.call(env)
- headers['Content-Language'] = I18n.locale.to_s
- [status, headers, body]
- ensure
- I18n.locale = old_locale
- end
- end
- private
- # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
- def accept_locale(env)
- accept_langs = env["HTTP_ACCEPT_LANGUAGE"]
- return if accept_langs.blank?
- languages_and_qvalues = accept_langs.split(",").map { |l|
- l += ';q=1.0' unless l =~ /;q=\d+(?:\.\d+)?$/
- l.split(';q=')
- }
- # gets tuple of supported locale with highest q-value
- lang = [nil, 0]
- languages_and_qvalues.each do |(locale, qvalue)|
- next if locale == '*'
- # locale could be en-GB and we only use en
- locale = locale.split('-').first.try(:to_sym)
- # check if locale is supported
- next unless I18n.available_locales.include?(locale)
- # return the new locale if its priority is higher
- lang = [locale, qvalue] if qvalue.to_f >= lang[1].to_f
- end
- lang.first
- end
- end
- ~
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement