[IMP] translate: add add/radd methods on _lt class

In order to ease the usage of lazy translation, add the possibility to
add the _lt objects together and with strings.

Adding two _lt objects together or to a string will execute their
translation, so these operations still must be done once the user's
language has been defined.

For example, this is now possible:

    MESSAGES = {
        1: _lt("Hello, world!"),
        2: _lt("Lorem ipsum"),
    }

    def get_text(code):
        return _("Text is: ") + MESSAGES[code]

closes odoo/odoo#60844

X-original-commit: c4596664e5514018c565eaf14b93e000d972bd30
Signed-off-by: Martin Trigaux (mat) <mat@odoo.com>
Signed-off-by: Paul Morelle <madprog@users.noreply.github.com>
This commit is contained in:
Paul Morelle
2020-10-27 15:18:38 +00:00
parent c4beae62dd
commit 43dd5c70d1
2 changed files with 20 additions and 0 deletions
@@ -205,6 +205,10 @@ class TestTermCount(common.TransactionCase):
context = {'lang': "tlh"}
self.assertEqual(str(TRANSLATED_TERM), "tlhIngan", "The lazy code translation was not applied")
self.assertEqual("Do you speak " + TRANSLATED_TERM, "Do you speak tlhIngan", "str + _lt concatenation failed")
self.assertEqual(TRANSLATED_TERM + ", I speak it", "tlhIngan, I speak it", "_lt + str concatenation failed")
self.assertEqual(TRANSLATED_TERM + TRANSLATED_TERM, "tlhIngantlhIngan", "_lt + _lt concatenation failed")
def test_import_from_csv_file(self):
"""Test the import from a single CSV file works"""
with file_open('test_translation_import/i18n/dot.csv', 'rb') as f:
+16
View File
@@ -539,6 +539,22 @@ class _lt:
def __lt__(self, other):
raise NotImplementedError()
def __add__(self, other):
# Call _._get_translation() like _() does, so that we have the same number
# of stack frames calling _get_translation()
if isinstance(other, str):
return _._get_translation(self._source) + other
elif isinstance(other, _lt):
return _._get_translation(self._source) + _._get_translation(other._source)
return NotImplemented
def __radd__(self, other):
# Call _._get_translation() like _() does, so that we have the same number
# of stack frames calling _get_translation()
if isinstance(other, str):
return other + _._get_translation(self._source)
return NotImplemented
_ = GettextAlias()