You need to enable JavaScript to run this app. Rails如何将Loco导出的翻译字符串拆分写入独立YAML文件
优惠活动
大模型
产品
解决方案
定价
更多

Rails如何将Loco导出的翻译字符串拆分写入独立YAML文件

解决方案

核心思路是给dig获取到的目标翻译节点,手动补回缺失的上层嵌套键后再转YAML写入文件,具体实现逻辑如下:

1. 明确路径与键序列的映射关系

你需要先建立输出目录和对应翻译前缀键的映射,你的场景下映射规则为:

  • 输出目录 config/locales/views/api/v1/users 对应前缀键序列 ['views', 'api', 'v1', 'users']
  • 输出目录 config/locales/views/users 对应前缀键序列 ['views', 'users']
  • 输出目录 config/locales/views/posts 对应前缀键序列 ['views', 'posts']

2. 实现嵌套Hash重构方法

写一个工具方法,将目标内容按照指定的键序列生成完整的嵌套Hash,补回缺失的en根键和路径前缀键:

# 输入:键序列、最内层的内容值
# 输出:完整嵌套结构的Hash
def build_nested_hash(key_sequence, content)
  key_sequence.reverse.inject(content) do |nested, key|
    { key => nested }
  end
end

3. 批量处理拆分写入

遍历所有目标路径,完成内容提取、结构重构、文件写入的全流程:

require 'fileutils'
require 'yaml'

# 假设full_translations是你通过Loco导出YAML解析后得到的完整翻译Hash
full_translations = YAML.load(File.read('你的Loco导出YAML文件路径'))

# 配置你的目标映射列表
target_configs = [
  {
    key_prefix: ['views', 'api', 'v1', 'users'],
    output_dir: 'config/locales/views/api/v1/users'
  },
  {
    key_prefix: ['views', 'users'],
    output_dir: 'config/locales/views/users'
  },
  {
    key_prefix: ['views', 'posts'],
    output_dir: 'config/locales/views/posts'
  }
]

target_configs.each do |config|
  # 提取对应节点的翻译内容
  target_content = full_translations.dig('en', *config[:key_prefix])
  # 跳过不存在的翻译节点,避免生成空文件
  next if target_content.nil? || target_content.empty?

  # 补全上层嵌套结构,生成符合Rails要求的Hash结构
  output_content = build_nested_hash(['en', *config[:key_prefix]], target_content)

  # 自动创建输出目录
  FileUtils.mkdir_p(config[:output_dir])
  # 写入en.yml文件,去掉YAML默认生成的---文档标记,符合Rails项目的locales文件惯例
  output_file_path = File.join(config[:output_dir], 'en.yml')
  File.write(output_file_path, output_content.to_yaml.sub(/^---\n/, ''))
end

扩展说明

  • 如果需要支持多语言,只需要把硬编码的'en'替换为遍历你项目支持的语言列表即可
  • 该方案生成的YAML文件完全符合Rails i18n懒加载规则,不需要额外调整配置即可正常识别加载

内容的提问来源于stack exchange,提问作者Spa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 23:15:04