Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add matching method to find best match based on language first and

	secondarily region
  • Loading branch information...
commit 7e2518a065065eb63d8787b7de2960bbabebb825 1 parent d60a7c6
@pinkvelociraptor pinkvelociraptor authored grosser committed
Showing with 25 additions and 1 deletion.
  1. +19 −0 lib/http_accept_language.rb
  2. +6 −1 test/http_accept_language_test.rb
View
19 lib/http_accept_language.rb
@@ -55,6 +55,25 @@ def compatible_language_from(available_languages)
end.compact.first
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
7 test/http_accept_language_test.rb
@@ -37,12 +37,17 @@ def test_should_find_first_compatible_from_user_preferred
request.env['HTTP_ACCEPT_LANGUAGE'] = 'en-us,de-de'
assert_equal 'en', request.compatible_language_from(%w{de en})
end
-
+
def test_should_accept_symbols_as_available_languages
request.env['HTTP_ACCEPT_LANGUAGE'] = 'en-us'
assert_equal :"en-HK", request.compatible_language_from([:"en-HK"])
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
Please sign in to comment.
Something went wrong with that request. Please try again.