Why locale setting in Rails acts as global (when using Thin)?

前端 未结 2 587
鱼传尺愫
鱼传尺愫 2021-02-01 20:31

I just realized that the recommended Rails way to set locale in your controller

before_filter :set_locale

def set_locale
  I18n.locale = params[:locale] || I18n         


        
2条回答
  •  借酒劲吻你
    2021-02-01 21:09

    Recommended code from above does not set locale globally it sets it by request.

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

    Code is usually place in BaseController so before each page is render it is triggered and set. There is no race conditions since every page will trigger this code and I18n locale will be calculated there. You can expand this to let's say looks for users locale, than session locale, than request params, than uses English.

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

    In other words if you set local on one page let's say in home controller to german and got to dashboard controller you will see default language (english). Since change is not global. That is why code is placed in base controller. Hope it makes sense.

提交回复
热议问题