feat: add locale extraction and sanitization methods

- Implemented `extract_locale_from_accept_language_header` to
  retrieve the user's preferred language from the request.
- Added `sanitize_locale` for validating and sanitizing locale
  inputs against available locales.
- Updated `set_locale` method to prepare for incorporating
  browser language preference handling.

These changes enhance the application's ability to set the locale
based on the user's browser settings, paving the way for better
internationalization support.
This commit is contained in:
songtianlun 2025-02-22 00:13:35 +08:00
parent bd42833953
commit 80ceac5d94

View File

@ -79,6 +79,30 @@ class ApplicationController < ActionController::Base
def set_locale
I18n.locale = extract_locale || I18n.default_locale
I18n.fallbacks[I18n.locale] = [ I18n.locale, I18n.default_locale ].uniq
# 如果URL已经包含语言前缀跳过处理
# return if params[:locale].present?
# 获取浏览器语言并转换为支持的语言代码
# locale = sanitize_locale(extract_locale_from_accept_language_header)
# I18n.with_locale(locale, &action)
# 重定向到带有语言前缀的相同路径
# redirect_to "/#{locale}#{request.fullpath}"
end
def extract_locale_from_accept_language_header
accept_language = request.env["HTTP_ACCEPT_LANGUAGE"].to_s
# 修改正则表达式以匹配 'zh-CN' 这样的格式
if (full_locale = accept_language.scan(/^[a-z]{2}-[A-Z]{2}/).first)
full_locale
else
# 否则只匹配语言代码 (例如 'en')
accept_language.scan(/^[a-z]{2}/).first || I18n.default_locale.to_s
end
end
def sanitize_locale(locale)
# 直接使用 I18n.available_locales
locale = locale.to_sym
I18n.available_locales.include?(locale) ? locale : I18n.default_locale
end
def extract_locale