adding path_prefix in root_url

397 views Asked by At

I have added localization in my website and it is working fine, except two points

  1. When I open website for example www.test.help.com it shows this url instead it should also show locale as I am using path_prefix in my application controller.
  2. When I click to change the language,the url is not changing instantly

here is my code snippet

application.rb

    include HttpAcceptLanguage::AutoLocale
    before_action :set_locale

   def default_url_options(options = {})
{ :path_prefix => I18n.locale }

 end

def set_locale
if cookies[:educator_locale] && I18n.available_locales.include?(cookies[:educator_locale].to_sym)
  l = cookies[:educator_locale].to_sym
else
  if params[:path_prefix].present?
    l = params[:path_present]
    cookies.permanent[:educator_locale] = l
  else
    if (http_accept_language.preferred_language_from(http_accept_language.user_preferred_languages).include? "en")
       l = 'en'
       cookies.permanent[:educator_locale] = l
    end
    if ( http_accept_language.preferred_language_from(http_accept_language.user_preferred_languages).include? "fr")
      l = 'fr'
      cookies.permanent[:educator_locale] = l
    end
  end
  cookies.permanent[:educator_locale] = l
end
I18n.locale = l
end

My setting controller

 def change_locale
l = params[:locale].to_s.strip.to_sym
# puts "---------"                                                                                                                                                                                             
# puts l                                                                                                                                                                                                       
l = I18n.default_locale unless I18n.available_locales.include?(l)
cookies.permanent[:educator_locale] = l
url_hash = Rails.application.routes.recognize_path URI(request.referer).path    url_hash[:locale] =l                                                                                                                                                                                         
redirect_to url_hash

end

Then my routes

 get '/change_locale/:locale', to: 'settings#change_locale', as: :change_locale
 get "home/index"
   root 'home#index'

Once I click on any link, then path prefix is visible but not directly on opening the website.

1

There are 1 answers

5
Ugo Mare On BEST ANSWER

When you arrive on any url for the first on the application (root_url, users_url ...) the url is displayed in your web browser before you entrer in set_locale. Then if you visit an other link in the application the locale will be added in the url. But the translations will works anyway with the locale you setted in I18n.locale.