I am trying to use request.location
(geocoder gem), to set the locale appropriately to the clients IP address.
This is what I've got:
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'
}
Using the parameter params[:locale]
, everything works just fine. But without the parameter it just defaults to en
, always.
What am I doing wrong here?