Browse files

Merge branch 'language_region_compatible' into all

  • Loading branch information...
2 parents 4e8eb4c + 7e2518a commit c4a6b716671a3cd332550c6b59825d53d6fd5a6f @grosser grosser committed Jul 12, 2012
Showing with 24 additions and 0 deletions.
  1. +19 −0 lib/http_accept_language.rb
  2. +5 −0 test/http_accept_language_test.rb
View
19 lib/http_accept_language.rb
@@ -71,6 +71,25 @@ def sanitize_available_locales(available_languages)
end
end
+ # Returns the first of the user preferred languages that is
+ # also found in available languages. Finds best fit by matching on
+ # primary language first and secondarily on region. If no matching region is
+ # found, return the first language in the group matching that primary language.
+ #
+ # Example:
+ #
+ # request.language_region_compatible(available_languages)
+ #
+ def language_region_compatible_from(available_languages)
+ available_languages = sanitize_available_locales(available_languages)
+ user_preferred_languages.map do |x| #en-US
+ lang_group = available_languages.select do |y| # en
+ y = y.to_s
+ x.split('-', 2).first == y.split('-', 2).first
+ end
+ lang_group.find{|l| l == x} || lang_group.first #en-US, en-UK
+ end.compact.first
+ end
end
if defined?(ActionDispatch::Request)
ActionDispatch::Request.send :include, HttpAcceptLanguage
View
5 test/http_accept_language_test.rb
@@ -47,6 +47,11 @@ def test_should_sanitize_available_language_names
assert_equal ["en-UK", "en-US", "ja-JP", "pt-BR"], request.sanitize_available_locales(%w{en_UK-x3 en-US-x1 ja_JP-x2 pt-BR-x5})
end
+ def test_should_find_most_compatible_language_from_user_preferred
+ request.env['HTTP_ACCEPT_LANGUAGE'] = 'ja,en-gb,en-us,fr-fr'
+ assert_equal "ja-JP", request.language_region_compatible_from(%w{en-UK en-US ja-JP})
+ end
+
private
def request
@request ||= MockedCgiRequest.new

0 comments on commit c4a6b71

Please sign in to comment.