]> git.openstreetmap.org Git - rails.git/blob - vendor/plugins/http_accept_language/lib/http_accept_language.rb
Have a nice translated alt and title for the sotm and donation.
[rails.git] / vendor / plugins / http_accept_language / lib / http_accept_language.rb
1 module HttpAcceptLanguage
2
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.
5   #
6   # Example:
7   #
8   #   request.user_preferred_languages
9   #   # => [ 'nl-NL', 'nl-BE', 'nl', 'en-US', 'en' ]
10   #
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+$/
14       l.split(';q=')
15     end.sort do |x,y|
16       raise "Not correctly formatted" unless x.first =~ /^[a-z\-]+$/i
17       y.last.to_f <=> x.last.to_f
18     end.collect do |l|
19       l.first.downcase.gsub(/-[a-z]+$/i) { |x| x.upcase }
20     end
21   rescue # Just rescue anything if the browser messed up badly.
22     []
23   end
24
25   # Finds the locale specifically requested by the browser.
26   #
27   # Example:
28   #
29   #   request.preferred_language_from I18n.available_locales
30   #   # => 'nl'
31   #
32   def preferred_language_from(array)
33     (user_preferred_languages & array.collect { |i| i.to_s }).first
34   end
35
36   # Returns the first of the user_preferred_languages that is compatible
37   # with the available locales. Ignores region.
38   #
39   # Example:
40   #
41   #   request.compatible_language_from I18n.available_locales
42   #
43   def compatible_language_from(array)
44     user_preferred_languages.map do |x|
45       x = x.to_s.split("-")[0]
46       array.find do |y|
47         y.to_s.split("-")[0] == x
48       end
49     end.compact.first
50   end
51
52 end