Tintin81
Tintin81

Reputation: 10207

Why namespace YAML localization files in Rails?

I am localizing a Rails app and I wonder why people do this:

# de.yml
helpers:
  select:
    prompt: "Bitte wählen..."
  submit:
    create: "Erstellen"
    submit: "Speichern"
    update: "Aktualisieren"

# some_view.html.erb
f.submit t('helpers.submit.update')

This seems to be the standard way of doing it.

But why not just do this instead:

# de.yml
prompt: "Bitte wählen..."
create: "Erstellen"
submit: "Speichern"
update: "Aktualisieren"

# some_view.html.erb
f.submit t('update')

What's the point of namespacing YAML files anyway? It just forces me to repeat the same paths (helpers.submit.update) all the time.

I don't get it...

Can anybody help me out here?

Upvotes: 1

Views: 737

Answers (2)

kr1
kr1

Reputation: 7485

if we leave aside the need for namespaces for the localization of dates and active record messages, gems and plugins.... there are a number of advantages in namespacing your own i18n data, especially when applications become complex and/or evolve over time:

  • it allows you to change the translation for a key for special cases, e.g. when you add a new language in which e.g. the creation of a message does not use the same word as the creation of a picture.
  • namespaced files are much easier to translate and maintain (you don't have to check the code to see, for example, if all occurrences of create can be translated with erstellen in the other language).
    this point becomes even more important if you hire external translators.
  • navigating the huge amount of keys and locating those in need of modification is easier, once the project gets big.

if, on the other hand, only programmers touch the yaml-files and your project is not big, I agree with you, go with the flat file.
in this scenario, even fake namespaces like messages_create or pictures_create can have the advantage that they are easier to locate in textfiles, with grep/ack, etc.

Upvotes: 2

Daniel Evans
Daniel Evans

Reputation: 6818

The reason is quite simple, in a normal rails app you may have hundreds or thousands of different values. These values may have the same name but have subtle differences. If you went only top level, as you are saying, then they easily become ambiguous: you won't know which labels belong with which views/models.

Imagine this:

name_missing: "you must enter a name"

If you were to see that in a YAML file you wouldn't know if that is meant to be used for a product name a user name or something else. So you would have to search your code and see where it is used.

Whereas, something like:

product:
  validation_errors:
    name_missing: "you must enter a name"

is unambiguous.

It may seem arbitrary to see a huge tree of fields, but when dealing with thousands or tens of thousands of labels and copy snippets organization is critical to maintainability.

Upvotes: 2

Related Questions