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 # Finds the locale specifically requested by the browser.
29 # request.preferred_language_from I18n.available_locales
32 def preferred_language_from(array)
33 (user_preferred_languages & array.collect { |i| i.to_s }).first
36 # Returns the first of the user_preferred_languages that is compatible
37 # with the available locales. Ignores region.
41 # request.compatible_language_from I18n.available_locales
43 def compatible_language_from(array)
44 user_preferred_languages.map do |x|
45 x = x.to_s.split("-")[0]
47 y.to_s.split("-")[0] == x