Skip to content

Scope translations to locale#15

Merged
virolea merged 4 commits intomainfrom
scoped-translations
Sep 30, 2024
Merged

Scope translations to locale#15
virolea merged 4 commits intomainfrom
scoped-translations

Conversation

@virolea
Copy link
Owner

@virolea virolea commented Sep 30, 2024

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.

def notify_translated_models
registered_classes_for_translations.each { |klass| klass.translated_in(self) }
end

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

@virolea virolea force-pushed the scoped-translations branch from 7579f87 to 823ef89 Compare September 30, 2024 11:00
@virolea virolea force-pushed the scoped-translations branch from cc46179 to 1c76451 Compare September 30, 2024 13:15
@virolea virolea marked this pull request as ready for review September 30, 2024 13:28
@virolea
Copy link
Owner Author

virolea commented Sep 30, 2024

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.

@virolea virolea merged commit 4c30a62 into main Sep 30, 2024
@virolea virolea deleted the scoped-translations branch September 30, 2024 13:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Eager load translations for a given key through the global Rosetta.locale variable in Admin

1 participant