[facets] provide a generic per-classification facet
authorAdrien Di Mascio <Adrien.DiMascio@logilab.fr>
Tue, 22 Sep 2009 19:20:43 +0200
changeset 66 82fefda182ea
parent 65 0049b8d1375c
child 67 52d02ce68893
[facets] provide a generic per-classification facet
views.py
--- a/views.py	Tue Sep 22 15:02:53 2009 +0200
+++ b/views.py	Tue Sep 22 19:20:43 2009 +0200
@@ -9,6 +9,7 @@
 from logilab.common.decorators import monkeypatch
 from logilab.mtconverter import xml_escape
 
+from cubicweb import Unauthorized
 from cubicweb.selectors import implements, rql_condition, relation_possible
 from cubicweb.view import EntityView
 from cubicweb.common.mixins import TreePathMixIn
@@ -134,6 +135,57 @@
         return vocab
 
 
+class ClassificationFacet(facet.RelationFacet):
+    """abstract per-classification facet
+
+    subclasses must define their own id the classification name, e.g :
+
+    class Classifaction1Facet(ClassificationFacet):
+        id = 'classif1'
+        classification = u'classification1'
+
+    """
+    __abstract__ = True
+    classification = None
+    rtype = 'applied_to'
+    role = 'object'
+
+    def vocabulary(self):
+        """return vocabulary for this facet, eg a list of 2-uple (label, value)
+        """
+        rqlst = self.rqlst
+        rqlst.save_state()
+        try:
+            mainvar = self.filtered_variable # X
+            keyword_var = rqlst.make_variable() # K
+            keyword_name_var = rqlst.make_variable() # KN
+            classif_var = rqlst.make_variable() # C
+            classif_name_var = rqlst.make_variable() # CN
+            rqlst.add_relation(keyword_var, 'applied_to', mainvar) # K applied_to X
+            rqlst.add_relation(keyword_var, 'name', keyword_name_var) # K name KN
+            rqlst.add_relation(keyword_var, 'included_in', classif_var) # K included_in C
+            # C name "classification-name"
+            rqlst.add_constant_restriction(classif_var, 'name', self.classification, 'String')
+            rqlst.add_selected(keyword_var)
+            rqlst.add_selected(keyword_name_var)
+            # ORDERBY KN
+            rqlst.add_sort_var(keyword_name_var, True)
+            try:
+                rset = self.req.execute(rqlst.as_string(), self.rset.args,
+                                        self.rset.cachekey)
+            except Unauthorized:
+                return []
+        finally:
+            rqlst.recover()
+        return self.rset_vocabulary(rset)
+
+    @property
+    def title(self):
+        return self.req._(self.classification)
+
+    def support_and(self):
+        return False
+
 # add some classification schema related methods to the Jsoncontroller ########
 
 @monkeypatch(basecontrollers.JSonController)