discourse/app/models/concerns/localizable.rb
Natalie Tay 6cc063b845
FEATURE: Serve localized content in the site's default locale when user's language is unsupported (#36160)
The content localization feature we have (e.g. on meta) currently
assumes that everyone has set their user preferences language to
a language that we support.

If Eleni sets Greek as her Interface language, it is a non-supported
language. Posts written in Chinese or French will remain in Chinese or
French, as there is no Greek translation.

The commit shows Eleni localized posts in English (i.e. site default locale)
when a post is written in a different language. A site setting
`content_localization_use_default_locale_when_unsupported` is default
true and introduced.
2025-11-21 17:19:04 +08:00

37 lines
1.3 KiB
Ruby
Vendored

# frozen_string_literal: true
module Localizable
extend ActiveSupport::Concern
included { has_many :localizations, class_name: "#{model_name}Localization", dependent: :destroy }
# Returns the localization for (in order of priority):
# - the given locale,
# - or the best match if an exact match is not found
# - or the site default locale if `content_localization_use_default_locale_when_unsupported` enabled
#
# The query used to find the localization is optimized for performance, and assumes
# that localizations are indexed by locale, and have been preloaded.
# @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
if match = localizations.find { |l| LocaleNormalizer.is_same?(l.locale, locale_str) }
return match
end
if SiteSetting.content_localization_use_default_locale_when_unsupported
default_locale = SiteSetting.default_locale.to_s.sub("-", "_")
localizations.find { |l| LocaleNormalizer.is_same?(l.locale, default_locale) }
end
end
def in_user_locale?
LocaleNormalizer.is_same?(locale, I18n.locale)
end
end