Use objects factory in renderers vocabulary
authorThierry Florac <thierry.florac@onf.fr>
Fri, 25 May 2018 08:04:24 +0200
changeset 556 8f3c10b301ea
parent 555 8e8a14452567
child 557 a78ade534b97
Use objects factory in renderers vocabulary
src/pyams_content/features/renderer/__init__.py
--- a/src/pyams_content/features/renderer/__init__.py	Fri May 25 08:03:41 2018 +0200
+++ b/src/pyams_content/features/renderer/__init__.py	Fri May 25 08:04:24 2018 +0200
@@ -20,6 +20,7 @@
 
 # import packages
 from pyams_utils.adapter import adapter_config
+from pyams_utils.factory import get_object_factory
 from pyams_utils.request import check_request
 from zope.interface import implementer
 from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
@@ -30,9 +31,16 @@
     """Renderer mixin interface"""
 
     renderer = None
+    """Attribute used to store selected content renderer.    
+    Subclasses should generally override this attribute to define a "Choice" field property based
+    on a given renderers vocabulary. 
+    """
+
     renderer_interface = IContentRenderer
+    """Content renderer interface"""
 
     def get_renderer(self, request=None):
+        """Get rendering adapter based on selected renderer name"""
         if request is None:
             request = check_request()
         return request.registry.queryMultiAdapter((self, request), self.renderer_interface, name=self.renderer or '')
@@ -54,17 +62,26 @@
 
 
 class RenderersVocabulary(SimpleVocabulary):
-    """Renderers vocabulary"""
+    """Renderers vocabulary base class"""
 
     content_interface = IRenderedContent
-    content_factory = RenderedContentMixin
+    """Interface used to check current context"""
+
+    content_factory = None
+    """Factory used to create a new context if current context doesn't implements required interface.
+    If no factory is given, vocabulary is looking for default object factory for given interface.
+    """
 
     def __init__(self, context=None):
         request = check_request()
         translate = request.localizer.translate
         registry = request.registry
         if not self.content_interface.providedBy(context):
-            context = self.content_factory()
+            factory = self.content_factory
+            if factory is None:
+                factory = get_object_factory(self.content_interface)
+            if factory is not None:
+                context = factory()
         terms = [SimpleTerm(name, title=translate(adapter.label))
                  for name, adapter in sorted(registry.getAdapters((context, request), IContentRenderer),
                                              key=lambda x: x[1].weight)]