discourse/app/models/concerns/localizable.rb
Natalie Tay b4526201ab
FEATURE: Localize topic titles and category names in crawler view (#34212)
If a site has `SiteSetting.content_localization_enabled = true`, we want
to start serving localized content.

This commit
- affects only anon topic lists like /latest, /top, /categories. 
- fixes an existing N+1 when loading localized category names on topic
lists
- updates the locale query param from `?lang=ja` to `?tl=ja`

| before | after |
|---|---|
| <img width="1264" height="831" alt="Screenshot 2025-08-11 at 3 18
09 PM"
src="https://github.com/user-attachments/assets/52023fbc-1444-4a01-95a3-7d7376a8ffd3"
/> mixed | <img width="1264" height="831" alt="Screenshot 2025-08-11 at
3 17 47 PM"
src="https://github.com/user-attachments/assets/b6e6ca17-de90-409f-9251-eea6e9b4ce88"
/> site default locale |
| <img width="1264" height="831" alt="Screenshot 2025-08-11 at 3 23
31 PM"
src="https://github.com/user-attachments/assets/d927b0d6-3a43-4ecb-8a9b-d1b97ae59cfc"
/> | <img width="1264" height="831" alt="Screenshot 2025-08-11 at 3 23
42 PM"
src="https://github.com/user-attachments/assets/d357b52b-396e-4f2d-bb47-7cc2485cf9ca"
/> with lang=ja |
2025-08-12 10:57:21 +08:00

22 lines
866 B
Ruby

# frozen_string_literal: true
module Localizable
extend ActiveSupport::Concern
included { has_many :localizations, class_name: "#{model_name}Localization", dependent: :destroy }
# Returns the localization for the given locale, or the best match if an exact match is not found.
# The query used to find the localization is optimized for performance, and assumes
# that localizations are indexed by locale, and have been preloaded where necessary.
# @return [Localization, nil] the localization object for the given locale, or nil if no match is found.
def get_localization(locale = I18n.locale)
locale_str = locale.to_s.sub("-", "_")
# prioritise exact match
if match = localizations.find { |l| l.locale == locale_str }
return match
end
localizations.find { |l| LocaleNormalizer.is_same?(l.locale, locale_str) }
end
end