在轨道上的ruby中自动设置区域设置

如何在rails上的ruby上自动设置语言环境? 例如,如果网页在西class牙打开,那么locale = es,同样如果它在英国,那么locale = en和类似的?

请帮帮我。

尝试使用gem geocoder geocoder和i18n_data gem,并将一个before_filter放到一个方法中

 def checklocale I18n.locale = I18nData.country_code(request.location.country) end 

你可以在ApplicationController像这样实现它:

 class ApplicationController < ActionController::Base before_filter :set_locale # [...] def set_locale I18n.locale = extract_locale_from_accept_language_header end private def extract_locale_from_accept_language_header request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[az]{2}/).first.presence || 'en' end # [...] end 

它将“检查”收到的请求,找到客户端浏览器的语言并将其设置为I18n语言环境。

请查看关于I18n的RubyOnRails指南以获取进一步的说明。

如果您的应用不支持此语言环境,您甚至可以从标题中“过滤”提取的语言环境(强烈推荐!),并使用带有else 的“默认语言环境” 。 像这样的东西:

 def extract_locale_from_accept_language_header case request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[az]{2}/).first when 'en' 'en' when 'fr' 'fr' when 'es' 'es' else 'en' end end 

或修订版(2018年)

 ALLOWED_LOCALES = %w( fr en es ).freeze DEFAULT_LOCALE = 'en'.freeze def extract_locale_from_header browser_locale = request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[az]{2}/).first if ALLOWED_LOCALES.include?(browser_locale) browser_locale else DEFAULT_LOCALE end end 

包括这是ApplicationControllerBaseController

 before_filter :set_locale def set_locale I18n.locale = params[:locale] || I18n.default_locale end 

这意味着将locale为默认值或使用来自请求的语言环境,优先级为请求中发送的语言环境。 如果要将此扩展为用户,会话,请求您可以执行此操作。

 def set_locale I18n.locale = @user.locale || session[:locale] || params[:locale] || I18n.default_locale end 

更多信息类似的问题。

如果我理解你的意思,你将不得不使用地理位置,根据他的IP获取用户位置,然后根据它设置语言环境,但你不能忘记设置一些默认值,万一你不能得到任何东西用户的IP。

我很遗憾地说,但我还没有在ruby上使用地理定位。 我对rubygems进行了快速研究,无法找到任何gem来简化你的工作。 =(

从Rails指南中 ,将此代码包含在ApplicationController中

 before_action :set_locale def set_locale I18n.locale = extract_locale_from_tld || I18n.default_locale end # Get locale from top-level domain or return nil if such locale is not available # You have to put something like: # 127.0.0.1 application.com # 127.0.0.1 application.it # 127.0.0.1 application.pl # in your /etc/hosts file to try this out locally def extract_locale_from_tld parsed_locale = request.host.split('.').last I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil end 

从本质上讲,这会从像application.co.id或example.com这样的URL中删除最终标识符(.en,.id等),并根据它设置区域设置。 如果用户来自您不支持的语言环境,则会返回默认语言环境 – 英语,除非另有设置。