From 3c0bc2d061004ae8b6958a22a8ff6d82621e0cb9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Gaya?= <sebastien.gaya@gmail.com>
Date: Thu, 9 Feb 2023 15:10:28 +0100
Subject: [PATCH] current website language is calculated model-side

---
 .../admin/communication/websites/application_controller.rb  | 6 +-----
 app/models/communication/website.rb                         | 6 ++++++
 2 files changed, 7 insertions(+), 5 deletions(-)

diff --git a/app/controllers/admin/communication/websites/application_controller.rb b/app/controllers/admin/communication/websites/application_controller.rb
index 5fccac61b..4d6e7c310 100644
--- a/app/controllers/admin/communication/websites/application_controller.rb
+++ b/app/controllers/admin/communication/websites/application_controller.rb
@@ -7,11 +7,7 @@ class Admin::Communication::Websites::ApplicationController < Admin::Communicati
   protected
 
   def current_website_language
-    @current_website_language ||= begin
-      language = @website.languages.find_by(iso_code: params[:lang])
-      language ||= @website.default_language
-      language
-    end
+    @current_website_language ||= @website.best_language_for(params[:lang])
   end
   helper_method :current_website_language
 
diff --git a/app/models/communication/website.rb b/app/models/communication/website.rb
index 9242fb535..a750fc647 100644
--- a/app/models/communication/website.rb
+++ b/app/models/communication/website.rb
@@ -98,6 +98,12 @@ class Communication::Website < ApplicationRecord
     dependencies
   end
 
+  def best_language_for(iso_code)
+    # We look for the language by the ISO code in the websites languages.
+    # If not found, we fallback to the default language.
+    languages.find_by(iso_code: iso_code) || default_language
+  end
+
   protected
 
   def languages_must_include_default_language
-- 
GitLab