Advertisement
Guest User

Untitled

a guest
Jul 7th, 2014
403
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # inspired by: https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/locale.rb
  2.  
  3. class LocaleMiddleware
  4.   def initialize(app)
  5.     @app = app
  6.   end
  7.  
  8.   def call(env)
  9.     old_locale = I18n.locale
  10.  
  11.     begin
  12.       locale = accept_locale(env) || I18n.default_locale
  13.       env['rack.locale'] = I18n.locale = locale.to_s
  14.       status, headers, body = @app.call(env)
  15.       headers['Content-Language'] = I18n.locale.to_s
  16.       [status, headers, body]
  17.     ensure
  18.       I18n.locale = old_locale
  19.     end
  20.   end
  21.  
  22.   private
  23.  
  24.   # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
  25.   def accept_locale(env)
  26.     accept_langs = env["HTTP_ACCEPT_LANGUAGE"]
  27.     return if accept_langs.blank?
  28.  
  29.     languages_and_qvalues = accept_langs.split(",").map { |l|
  30.       l += ';q=1.0' unless l =~ /;q=\d+(?:\.\d+)?$/
  31.       l.split(';q=')
  32.     }
  33.  
  34.     # gets tuple of supported locale with highest q-value
  35.     lang = [nil, 0]
  36.     languages_and_qvalues.each do |(locale, qvalue)|
  37.       next if locale == '*'
  38.       # locale could be en-GB and we only use en
  39.       locale = locale.split('-').first.try(:to_sym)
  40.       # check if locale is supported
  41.       next unless I18n.available_locales.include?(locale)
  42.       # return the new locale if its priority is higher
  43.       lang = [locale, qvalue] if qvalue.to_f >= lang[1].to_f
  44.     end
  45.     lang.first
  46.   end
  47. end
  48. ~
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement