From 709f39c6ce6bb265269c4c6486d30d84e4f774a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javi=20Mart=C3=ADn?= Date: Wed, 22 May 2024 16:53:37 +0200 Subject: [PATCH] Handle unavailable locales in subscriptions There was an edge case where a user could configure a locale and then the application would change the locales to that one would no longer be available. In that case, we were getting a `I18n::InvalidLocale` exception when accessing the subscriptions page. So now, we're defaulting to `I18n.locale`. Note we're using `I18n.locale`instead of `I18n.default_locale` because `set_user_locale` is called inside the `switch_locale` block in `ApplicationController`, which already sets `I18n.locale` based on `I18n.default_locale`. --- app/controllers/subscriptions_controller.rb | 6 +++++- spec/controllers/subscriptions_controller_spec.rb | 8 ++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/app/controllers/subscriptions_controller.rb b/app/controllers/subscriptions_controller.rb index acbdb02d8..315905001 100644 --- a/app/controllers/subscriptions_controller.rb +++ b/app/controllers/subscriptions_controller.rb @@ -32,8 +32,12 @@ class SubscriptionsController < ApplicationController def set_user_locale(&action) if params[:locale].blank? - session[:locale] = I18n.available_locales.find { |locale| locale == @user.locale&.to_sym }.to_s + session[:locale] = find_locale.to_s end I18n.with_locale(session[:locale], &action) end + + def find_locale + I18n.available_locales.find { |locale| locale == @user.locale&.to_sym } || I18n.locale + end end diff --git a/spec/controllers/subscriptions_controller_spec.rb b/spec/controllers/subscriptions_controller_spec.rb index dd1934dd6..1e1124125 100644 --- a/spec/controllers/subscriptions_controller_spec.rb +++ b/spec/controllers/subscriptions_controller_spec.rb @@ -27,5 +27,13 @@ describe SubscriptionsController do expect(session[:locale]).to eq "es" end + + it "only accepts available locales" do + create(:user, locale: "wl", subscriptions_token: "mytoken") + + get :edit, params: { token: "mytoken" } + + expect(session[:locale]).to eq "en" + end end end