Permalink
Browse files

Add sanitization method for available locales

  • Loading branch information...
1 parent d60a7c6 commit 4e8eb4cb78f11b956277e587e2701c1d8a7de345 @pinkvelociraptor pinkvelociraptor committed with grosser Aug 24, 2011
Showing with 21 additions and 1 deletion.
  1. +16 −0 lib/http_accept_language.rb
  2. +5 −1 test/http_accept_language_test.rb
@@ -55,6 +55,22 @@ def compatible_language_from(available_languages)
end.compact.first
end
+ # Returns a supplied list of available locals without any extra application info
+ # that may be attached to the locale for storage in the application.
+ #
+ # Example:
+ # [ja_JP-x1, en-US-x4, en_UK-x5, fr-FR-x3] => [ja-JP, en-US, en-UK, fr-FR]
+ #
+ def sanitize_available_locales(available_languages)
+ available_languages.map do |avail|
+ split_locale = avail.split(/[_-]/)
+
+ split_locale.map do |e|
+ e unless e.match(/x|[0-9*]/)
+ end.compact.join("-")
+ end
+ end
+
end
if defined?(ActionDispatch::Request)
ActionDispatch::Request.send :include, HttpAcceptLanguage
@@ -37,12 +37,16 @@ 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_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
+
private
def request
@request ||= MockedCgiRequest.new

0 comments on commit 4e8eb4c

Please sign in to comment.