* turn tidy_html_hook into a regular application hook tls-sprint
authorsylvain.thenault@logilab.fr
Thu, 12 Mar 2009 18:40:24 +0100
branchtls-sprint
changeset 1098 739d4dce9b19
parent 1097 611bacbbe001
child 1099 2353d1472094
* turn tidy_html_hook into a regular application hook * use format_fields instead of formatted_attrs method * drop formatted_attrs
entity.py
server/hooks.py
sobjects/hooks.py
test/unittest_entity.py
--- a/entity.py	Thu Mar 12 16:34:13 2009 +0100
+++ b/entity.py	Thu Mar 12 18:40:24 2009 +0100
@@ -461,17 +461,6 @@
             needcheck = False
         return mainattr, needcheck
 
-    @cached
-    def formatted_attrs(self):
-        """returns the list of attributes which have some format information
-        (i.e. rich text strings)
-        """
-        attrs = []
-        for rschema, attrschema in self.e_schema.attribute_definitions():
-            if attrschema.type == 'String' and self.has_format(rschema):
-                attrs.append(rschema.type)
-        return attrs
-
     @classmethod
     @obsolete('use method of the same name on the schema')
     def has_format(cls, attr):
--- a/server/hooks.py	Thu Mar 12 16:34:13 2009 +0100
+++ b/server/hooks.py	Thu Mar 12 18:40:24 2009 +0100
@@ -11,8 +11,6 @@
 
 from cubicweb import UnknownProperty, ValidationError, BadConnectionId
 
-from cubicweb.common.uilib import soup2xhtml
-
 from cubicweb.server.pool import Operation, LateOperation, PreCommitOperation
 from cubicweb.server.hookhelper import (check_internal_entity, previous_state,
                                      get_user_sessions, rproperty)
@@ -208,30 +206,6 @@
 
 
 
-class tidy_html_fields(object):
-    """tidy HTML in rich text strings
-
-    FIXME: (adim) the whole idea of having a class is to store the
-    event type. There might be another way to get dynamically the
-    event inside the hook function.
-    """
-    # FIXME hooks manager use func_name to register
-    func_name = 'tidy_html_field'
-    
-    def __init__(self, event):
-        self.event = event
-
-    def __call__(self, session, entity):
-        for attr in entity.formatted_attrs():
-            value = entity.get(attr)
-            # text was not changed
-            if self.event == 'before_add_entity':
-                fmt = entity.get('%s_format' % attr)
-            else:
-                fmt = entity.get_value('%s_format' % attr)
-            if value and fmt == 'text/html':
-                entity[attr] = soup2xhtml(value, session.encoding)
-
 
 class CheckRequiredRelationOperation(LateOperation):
     """checking relation cardinality has to be done after commit in
@@ -315,8 +289,6 @@
     hm.register_hook(cstrcheck_after_add_relation, 'after_add_relation', '')
     hm.register_hook(uniquecstrcheck_before_modification, 'before_add_entity', '')
     hm.register_hook(uniquecstrcheck_before_modification, 'before_update_entity', '')
-    hm.register_hook(tidy_html_fields('before_add_entity'), 'before_add_entity', '')
-    hm.register_hook(tidy_html_fields('before_update_entity'), 'before_update_entity', '')
 
 
 # user/groups synchronisation #################################################
--- a/sobjects/hooks.py	Thu Mar 12 16:34:13 2009 +0100
+++ b/sobjects/hooks.py	Thu Mar 12 18:40:24 2009 +0100
@@ -1,14 +1,16 @@
 """various library content hooks
 
 :organization: Logilab
-:copyright: 2001-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
 """
 __docformat__ = "restructuredtext en"
 
+from cubicweb.common.uilib import soup2xhtml
 from cubicweb.server.hooksmanager import Hook
 from cubicweb.server.pool import PreCommitOperation
 
+
 class AddUpdateEUserHook(Hook):
     """ensure user logins are stripped"""
     events = ('before_add_entity', 'before_update_entity',)
@@ -35,3 +37,24 @@
     
     def call(self, session, subj, rtype, obj):
         AutoDeleteBookmark(session, beid=subj)
+
+
+class TidyHtmlFields(Hook):
+    """tidy HTML in rich text strings"""
+    events = ('before_add_entity', 'before_update_entity')
+    accepts = ('Any',)
+
+    def call(self, session, entity):
+        for formatattr, attr in entity.e_schema.format_fields.iteritems():
+            try:
+                value = entity[attr]
+            except KeyError:
+                continue # no text to tidy
+            if isinstance(value, unicode): # filter out None and Binary
+                if self.event == 'before_add_entity':
+                    fmt = entity.get(formatattr)
+                else:
+                    fmt = entity.get_value(formatattr)
+                if fmt == 'text/html':
+                    entity[attr] = soup2xhtml(value, session.encoding)
+
--- a/test/unittest_entity.py	Thu Mar 12 16:34:13 2009 +0100
+++ b/test/unittest_entity.py	Thu Mar 12 18:40:24 2009 +0100
@@ -374,13 +374,6 @@
         e['content'] = u'été'
         self.assertEquals(e.printable_value('content'), e['content'])
         
-
-    def test_entity_formatted_attrs(self):
-        e = self.etype_instance('EUser')
-        self.assertEquals(e.formatted_attrs(), [])
-        e = self.etype_instance('File')
-        self.assertEquals(e.formatted_attrs(), ['description'])
-        
         
     def test_fulltextindex(self):
         e = self.etype_instance('File')