Refactoring Ruby on Rails i18n YAML files using dictionaries

后端 未结 4 1550
长发绾君心
长发绾君心 2020-12-08 14:55

This StackOverflow question gave me food for thought on what is a good structure for Rails i18n files, so I thought I\'d share another structure for refactoring Rails i18n y

4条回答
  •  醉酒成梦
    2020-12-08 15:34

    I just release a gem called i18n-recursive-lookup that allows a definition to contain embedded references to other definitions by introducing the special embedded marker ${}

    https://github.com/annkissam/i18n-recursive-lookup

    Using it you could refactor your example to:

    dictionary:
      email: Email
      name: Name
      password: Password
      confirmation: Confirmation
    
    activerecord:
      attributes:
        user:
          email: ${dictionary.email}
          name: ${dictionary.name}
          password: ${dictionary.password}
          password_confirmation: ${dictionary.confirmation}
      models:
        user: User
    users:
      fields:  
        email: ${dictionary.email}
        name: ${dictionary.name}
        password: ${dictionary.password}
        confirmation: ${dictionary.confirmation}
    sessions:
      new:
        email: ${dictionary.email}
        password: ${dictionary.password}
    

    The nice thing is that once compiled the translations are written back to the translation store so that all interpolation/recursive lookup happens once.

    I know this might not answer the more philosophical questions about what the 'right' way to DRY up translations is, but I thought it's a better alternative to using the & label reference YML hack.

提交回复
热议问题