Detect browser language in Rails

后端 未结 5 695
一个人的身影
一个人的身影 2020-12-30 01:04

How do you detect the users language (in RoR) as set in the browser? I will have a select box the user can use at anytime, but I\'d like to default to whatever their browser

5条回答
  •  余生分开走
    2020-12-30 01:31

    This is a really old question, but I like to mention that Rails guide has a description of how to detect user browser language.

    Below code is based on the solution from Ruby on Rails guide with improvements:

    • checks are there HTTP_ACCEPT_LANGUAGE - sometimes that header is missing for bots, and you will get errors in your error reporting tool
    • checks are language supported by your application

    code:

      def set_locale_based_on_browser
        locale = extract_locale_from_accept_language_header
    
        I18n.locale =
          if locale_valid?(locale)
            locale
          else
            :en
          end
      end
    
      private
    
      def locale_valid?(locale)
        I18n.available_locales.map(&:to_s).include?(locale)
      end
    
      def extract_locale_from_accept_language_header
        accept_language = request.env['HTTP_ACCEPT_LANGUAGE']
        return unless accept_language
    
        accept_language.scan(/^[a-z]{2}/).first
      end
    end
    

    More information about locale detection can be found in Ruby on Rails guide: https://guides.rubyonrails.org/i18n.html#choosing-an-implied-locale

提交回复
热议问题