【问题标题】:Rails: Setting locale appropriately to IP addressRails:将区域设置适当地设置为 IP 地址
【发布时间】:2017-03-11 11:00:10
【问题描述】:

我正在尝试使用request.location(geocoder gem),将区域设置适当地设置为客户端IP 地址。


这就是我所拥有的:

app/controllers/application_controller.rb

before_action :set_locale

private

def set_locale
    # get location with geocoder
    location = request.location

    # set locale through URL
    if params.has_key?(:locale)
        I18n.locale = params[:locale] || I18n.default_locale
    # set locale through user preference
    elsif current_user && current_user.locale.present?
        I18n.locale = current_user.try(:locale) || I18n.default_locale
    # set locale through geocoder detection of location
    elsif location.present? && location.country_code.present? && I18n.available_locales.include?(location.country_code)
        if location.country_code.include? "-"
            I18n.locale = location.country_code
        else
            I18n.locale = location.country_code.downcase
        end
    # set locale through HTTP detection of location
    elsif (request.env["HTTP_ACCEPT_LANGUAGE"] || "en").scan(/^[a-z]{2}/).first.present? && I18n.available_locales.include?((request.env["HTTP_ACCEPT_LANGUAGE"] || "en").scan(/^[a-z]{2}/).first)
        I18n.locale = (request.env["HTTP_ACCEPT_LANGUAGE"] || "en").scan(/^[a-z]{2}/).first
    end
end


config/application.rb

# i18n Translations
## load the subfolders in the locales
config.i18n.load_path += Dir["#{Rails.root.to_s}/config/locales/**/**/**/**/**/*.{rb,yml}"]
## set default locale
config.i18n.default_locale = 'en'
## provide locale fallbacks
config.i18n.enforce_available_locales = false
config.i18n.fallbacks = {
    'de-AT' => 'de', 'de-CH' => 'de', 'de-DE' => 'de',
    'en-AU' => 'en', 'en-CA' => 'en', 'en-GB' => 'en', 'en-IE' => 'en', 'en-IN' => 'en', 'en-NZ' => 'en', 'en-US' => 'en', 'en-ZA' => 'en'
}

使用参数params[:locale],一切正常。但如果没有参数,它总是默认为en。

我在这里做错了什么?

【问题讨论】:

    标签: ruby-on-rails ruby internationalization locale geocoding


    【解决方案1】:

    I18n.locale 默认情况下在请求之间不会被记住 - 您需要通过将其保存到会话中来自己实现它。设置I18n.locale后,可以使用:

    session[:locale] = I18n.locale
    

    然后把它拉回来:

    I18n.locale = params[:locale] || session[:locale] || I18n.default_locale
    # explicit params take precedence
    # otherwise use the remembered session value
    # fallback to the default for new users
    

    旁注:考虑移动您的location = request.location,使其不会一直运行。即使您没有使用数据,每次请求都会对性能造成小幅影响(以及地理编码服务查找)。


    举例来说,这是一种方法你可以这样做:

    def set_locale
        # explicit param can always override existing setting
        # otherwise, make sure to allow a user preference to override any automatic detection
        # then detect by location, and header
        # if all else fails, fall back to default
        I18n.locale = params[:locale] || user_pref_locale || session[:locale] || location_detected_locale || header_detected_locale || I18n.default_locale
    
        # save to session
        session[:locale] = I18n.locale
    end
    
    # these could potentially do with a bit of tidying up
    # remember to return `nil` to indicate no match
    
    def user_pref_locale
        return nil unless current_user && current_user.locale.present?
        current_user.locale
    end
    
    def location_detected_locale
        location = request.location
        return nil unless location.present? && location.country_code.present? && I18n.available_locales.include?(location.country_code)
        location.country_code.include?("-") ? location.country_code : location.country_code.downcase
    end
    
    def header_detected_locale
        return nil unless (request.env["HTTP_ACCEPT_LANGUAGE"] || "en").scan(/^[a-z]{2}/).first.present? && I18n.available_locales.include?((request.env["HTTP_ACCEPT_LANGUAGE"] || "en").scan(/^[a-z]{2}/).first)
        (request.env["HTTP_ACCEPT_LANGUAGE"] || "en").scan(/^[a-z]{2}/).first
    end
    

    【讨论】:

    • 奇怪的是,如果我添加以下内容:session[:locale] = params[:locale] if params[:locale] != session[:locale] 来更新会话数据,当设置了新的语言环境时,会导致应用程序在每次请求时回退到 en。 rails 是在后台设置这个参数吗?
    • @jonhue: session 将在请求之间被记住,但您的 params 可能包括也可能不包括 locale。要在每个页面上包含它,您需要在生成 URL 时将其从控制器传递到视图。最好的方法是将params[:locale] 视为任何现有设置的一次性覆盖,否则始终依赖session[:locale](如果已设置)
    • 顺便说一下,I18n 文档部分 (stackoverflow.com/documentation/ruby-on-rails/2772/…) 中有很好的代码示例,这可能有助于提供更全面的解释
    • 是的,在您的帖子之后,我尝试这样做。我遇到的问题是,当 session[:locale] 已经设置时。我无法通过检查unless session[:locale] 来覆盖它。我需要使用某种if params[:locale] 来为此做好准备。感觉就像 rails 会在后台自动设置,因为即使在 URL 中没有设置参数,它也会运行该代码。
    • @johnhue:我已经更新了答案以包含一个示例,希望这会让事情变得更清楚!警告购买者:这未经测试,但原则应该是合理的。
    猜你喜欢
    • 2012-09-22
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    相关资源
    最近更新 更多