today_ai_weather/app/models/concerns/translatable_name.rb
songtianlun bd42833953 feat: add translatable name module for countries and regions
- Introduced `TranslatableName` module to allow for
  localized names for `Country` and `Region` models.
- Updated views to display `localized_name` instead of
  `name` for improved internationalization.
- Refactored JSON serialization for `translations` attribute.
- Enhanced localization support by adding new languages:
  Japanese and Korean, with updated locale files.
- Removed outdated English and Chinese locales for countries
  and regions to clean up the codebase.
2025-02-21 23:46:25 +08:00

23 lines
852 B
Ruby
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# app/models/concerns/translatable_name.rb
module TranslatableName
extend ActiveSupport::Concern
def localized_name(default_locale = "en")
return name unless translations.present?
translations_hash = translations.is_a?(String) ? JSON.parse(translations) : translations
# 尝试完全匹配当前语言设置
current_locale = I18n.locale.to_s
return translations_hash[current_locale] if translations_hash[current_locale].present?
# 尝试匹配语言的基础部分(例如 'zh-CN' => 'zh'
base_locale = current_locale.split("-").first
matching_key = translations_hash.keys.find { |k| k.start_with?(base_locale) }
return translations_hash[matching_key] if matching_key.present?
# 如果没有匹配,返回默认语言的翻译或原始名称
translations_hash[default_locale] || name
end
end