1 module HttpAcceptLanguage
3 # Returns a sorted array based on user preference in HTTP_ACCEPT_LANGUAGE.
4 # Browsers send this HTTP header, so don't think this is holy.
8 # request.user_preferred_languages
9 # # => [ 'nl-NL', 'nl-BE', 'nl', 'en-US', 'en' ]
11 def user_preferred_languages
12 @user_preferred_languages ||= env['HTTP_ACCEPT_LANGUAGE'].split(',').collect do |l|
13 l += ';q=1.0' unless l =~ /;q=\d+\.\d+$/
16 raise "Not correctly formatted" unless x.first =~ /^[a-z\-]+$/i
17 y.last.to_f <=> x.last.to_f
19 l.first.downcase.gsub(/-[a-z]+$/i) { |x| x.upcase }
21 rescue # Just rescue anything if the browser messed up badly.
25 # Sets the user languages preference, overiding the browser
27 def user_preferred_languages=(languages)
28 @user_preferred_languages = languages
31 # Finds the locale specifically requested by the browser.
35 # request.preferred_language_from I18n.available_locales
38 def preferred_language_from(array)
39 (user_preferred_languages & array.collect { |i| i.to_s }).first
42 # Returns the first of the user_preferred_languages that is compatible
43 # with the available locales. Ignores region.
47 # request.compatible_language_from I18n.available_locales
49 def compatible_language_from(array)
50 user_preferred_languages.map do |x|
51 x = x.to_s.split("-")[0]
53 y.to_s.split("-")[0] == x