summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSouheil CHELFOUH <trollfot@gmail.com>2018-09-04 13:02:35 +0200
committerSouheil CHELFOUH <trollfot@gmail.com>2018-09-04 13:02:35 +0200
commitdafecabd80e3b9cda4fd96751479853361bb14be (patch)
tree20d8e44e0c7eee33ef6ff702df7460003b96e171
parentda547b8cafa05ccb35b570f1ad1a06d146712faa (diff)
downloadzope-i18n-dafecabd80e3b9cda4fd96751479853361bb14be.tar.gz
Added a simple decorator to handle plural integer formatting while returning the message string. Using now the 'plural' function of the catalog to determine the right default string to return.
-rw-r--r--src/zope/i18n/gettextmessagecatalog.py36
1 files changed, 22 insertions, 14 deletions
diff --git a/src/zope/i18n/gettextmessagecatalog.py b/src/zope/i18n/gettextmessagecatalog.py
index 884cf54..6a0dbe7 100644
--- a/src/zope/i18n/gettextmessagecatalog.py
+++ b/src/zope/i18n/gettextmessagecatalog.py
@@ -14,6 +14,7 @@
"""A simple implementation of a Message Catalog.
"""
+from functools import wraps
from gettext import GNUTranslations
from zope.i18n.interfaces import IGlobalMessageCatalog
from zope.interface import implementer
@@ -30,6 +31,18 @@ class _KeyErrorRaisingFallback(object):
ngettext = ungettext
+def plural_formatting(func):
+ @wraps(func)
+ def pformat(catalog, singular, plural, n, *args, **kwargs):
+ msg = func(catalog, singular, plural, n, *args, **kwargs)
+ try:
+ return msg % n
+ except TypeError:
+ # The message cannot be formatted : return it "raw".
+ return msg
+ return pformat
+
+
@implementer(IGlobalMessageCatalog)
class GettextMessageCatalog(object):
"""A message catalog based on GNU gettext and Python's gettext module."""
@@ -62,27 +75,22 @@ class GettextMessageCatalog(object):
'See IMessageCatalog'
return self._gettext(id)
+ @plural_formatting
def getPluralMessage(self, singular, plural, n):
'See IMessageCatalog'
- msg = self._ngettext(singular, plural, n)
- try:
- return msg % n
- except TypeError:
- return msg
+ return self._ngettext(singular, plural, n)
+ @plural_formatting
def queryPluralMessage(self, singular, plural, n, dft1=None, dft2=None):
'See IMessageCatalog'
try:
- msg = self._ngettext(singular, plural, n)
+ return self._ngettext(singular, plural, n)
except KeyError:
- if n == 1: # Please FIX using the language rule.
- msg = dft1
- else:
- msg = dft2
- try:
- return msg % n
- except TypeError:
- return msg
+ # Here, we use the catalog plural function to determine
+ # if `n` triggers a plural form or not.
+ if self._catalog.plural(n):
+ return dft2
+ return dft1
def queryMessage(self, id, default=None):
'See IMessageCatalog'