Permalink
Browse files

Rack::Locale: extract helper method

  • Loading branch information...
James A. Rosen
James A. Rosen committed Aug 19, 2012
1 parent 61a0471 commit 0c1a7ac13374012643444f847e5883a39bca9149
Showing with 20 additions and 15 deletions.
  1. +20 −15 lib/rack/contrib/locale.rb
View
@@ -8,26 +8,31 @@ def initialize(app)
def call(env)
old_locale = I18n.locale
- locale = nil
-
- # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
- if lang = env["HTTP_ACCEPT_LANGUAGE"]
- lang = lang.split(",").map { |l|
- l += ';q=1.0' unless l =~ /;q=\d+(?:\.\d+)?$/
- l.split(';q=')
- }.sort_by { |(locale, qvalue)|
- qvalue.to_f
- }.last
- locale = lang.first.split("-").first
- else
- locale = I18n.default_locale
- end
-
+ locale = accept_locale(env) || I18n.default_locale
locale = env['rack.locale'] = I18n.locale = locale.to_s
status, headers, body = @app.call(env)
headers['Content-Language'] = locale
I18n.locale = old_locale
[status, headers, body]
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.nil?
+
+ languages_and_qvalues = accept_langs.split(",").map { |l|
+ l += ';q=1.0' unless l =~ /;q=\d+(?:\.\d+)?$/
+ l.split(';q=')
+ }
+
+ lang = languages_and_qvalues.sort_by { |(locale, qvalue)|
+ qvalue.to_f
+ }.last
+
+ lang.first.split("-").first
+ end
end
end

0 comments on commit 0c1a7ac

Please sign in to comment.