【发布时间】: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