changeset 788:09531799bac2

Change `Translator` class to accept either a `gettext`-style function, or an object compatible with the `NullTranslations` / `GNUTranslations` interface.
author cmlenz
date Sun, 10 Aug 2008 20:32:13 +0000
parents 422a9dd01e9f
children 1b6968d31089
files genshi/filters/i18n.py genshi/filters/tests/i18n.py
diffstat 2 files changed, 42 insertions(+), 6 deletions(-) [+]
line wrap: on
line diff
--- a/genshi/filters/i18n.py
+++ b/genshi/filters/i18n.py
@@ -17,8 +17,9 @@
 """
 
 from compiler import ast
-from gettext import gettext
+from gettext import NullTranslations
 import re
+from types import FunctionType
 
 from genshi.core import Attrs, Namespace, QName, START, END, TEXT, START_NS, \
                         END_NS, XML_NAMESPACE, _ensure
@@ -91,7 +92,7 @@
     INCLUDE_ATTRS = frozenset(['abbr', 'alt', 'label', 'prompt', 'standby',
                                'summary', 'title'])
 
-    def __init__(self, translate=gettext, ignore_tags=IGNORE_TAGS,
+    def __init__(self, translate=NullTranslations(), ignore_tags=IGNORE_TAGS,
                  include_attrs=INCLUDE_ATTRS, extract_text=True):
         """Initialize the translator.
         
@@ -102,6 +103,10 @@
         :param extract_text: whether the content of text nodes should be
                              extracted, or only text in explicit ``gettext``
                              function calls
+
+        :note: Changed in 0.6: the `translate` parameter can now be either
+               a ``gettext``-style function, or an object compatible with the
+               ``NullTransalations`` or ``GNUTranslations`` interface
         """
         self.translate = translate
         self.ignore_tags = ignore_tags
@@ -126,7 +131,10 @@
         """
         ignore_tags = self.ignore_tags
         include_attrs = self.include_attrs
-        translate = self.translate
+        if type(self.translate) is FunctionType:
+            gettext = self.translate
+        else:
+            gettext = self.translate.ugettext
         if not self.extract_text:
             search_text = False
 
@@ -162,7 +170,7 @@
                     newval = value
                     if search_text and isinstance(value, basestring):
                         if name in include_attrs:
-                            newval = self.translate(value)
+                            newval = gettext(value)
                     else:
                         newval = list(self(_ensure(value), ctxt,
                             search_text=False)
@@ -190,7 +198,7 @@
                 if not msgbuf:
                     text = data.strip()
                     if text:
-                        data = data.replace(text, unicode(translate(text)))
+                        data = data.replace(text, unicode(gettext(text)))
                     yield kind, data, pos
                 else:
                     msgbuf.append(kind, data, pos)
@@ -201,7 +209,7 @@
             elif not skip and msgbuf and kind is END:
                 msgbuf.append(kind, data, pos)
                 if not msgbuf.depth:
-                    for event in msgbuf.translate(translate(msgbuf.format())):
+                    for event in msgbuf.translate(gettext(msgbuf.format())):
                         yield event
                     msgbuf = None
                     yield kind, data, pos
--- a/genshi/filters/tests/i18n.py
+++ b/genshi/filters/tests/i18n.py
@@ -13,6 +13,7 @@
 
 from datetime import datetime
 import doctest
+from gettext import NullTranslations
 from StringIO import StringIO
 import unittest
 
@@ -22,6 +23,22 @@
 from genshi.input import HTML
 
 
+class DummyTranslations(NullTranslations):
+
+    def __init__(self, catalog):
+        NullTranslations.__init__(self)
+        self._catalog = catalog
+
+    def ugettext(self, message):
+        missing = object()
+        tmsg = self._catalog.get(message, missing)
+        if tmsg is missing:
+            if self._fallback:
+                return self._fallback.ugettext(message)
+            return unicode(message)
+        return tmsg
+
+
 class TranslatorTestCase(unittest.TestCase):
 
     def test_translate_included_attribute_text(self):
@@ -391,6 +408,17 @@
           <p>Voh</p>
         </html>""", tmpl.generate().render())
 
+    def test_translate_with_translations_object(self):
+        tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/"
+            xmlns:i18n="http://genshi.edgewall.org/i18n">
+          <p i18n:msg="" i18n:comment="As in foo bar">Foo</p>
+        </html>""")
+        translations = DummyTranslations({'Foo': 'Voh'})
+        tmpl.filters.insert(0, Translator(translations))
+        self.assertEqual("""<html>
+          <p>Voh</p>
+        </html>""", tmpl.generate().render())
+
 
 class ExtractTestCase(unittest.TestCase):
 
Copyright (C) 2012-2017 Edgewall Software