virolea / rosetta

Unobstrusive Internationalization solution for Rails applications.
MIT License
53 stars 1 forks source link

Scope translations to locale #15

Closed virolea closed 1 week ago

virolea commented 1 week ago

Closes #3

In this PR we move away from using the Rosetta.locale global to scope translations for a given key to a given locale.

The design and its pros and cons were previously explained in #3.

While working on #10, it became clear that we needed dedicated getters and setters for scoped translations. Things like:

translation_key = Rosetta::TranslationKey.create(value: "hello") 
translation_key.update(value_fr: "bonjour") 
translation_key.fr_translation # => Rosetta::Translation(value: "bonjour")

A new Translated module is introduced, heavily inspired by what's been implemented in ActiveStorage in Rails itself. The main advantage of this design is that we can defer the setup of the has_one association when the parent model is saved.

Additionnal logic can be implemented in Rosetta::Translated::Create and Rosetta::Translated::Delete to account for future needs and design evolution.

Finally, the main blocker for implementing this was that we know available locales only at runtime. This is fine for existing locales, but new locales would not be associated to the TranslationKey model.

This is fixed by adding a listener to the after a new locale is created. Translated model are notified of the newly created locale and appropriate associations are setup.

https://github.com/virolea/rosetta/blob/dc0efb091088ddf0cc15486f5cf4151d1baf930c/app/models/rosetta/locale.rb#L36-L38

Note: the corollary is that locale codes can't be updated after the locale is created.

virolea commented 1 week ago

I don't understand why tests are failing. Everything runs smoothly on my end with paralellization. It seems like new code is not considered. Maybe caching?

Merging as is, I'll investigate more if this continues on main.