web/__init__.py
branchtls-sprint
changeset 1635 866563e2d0fc
parent 1181 620ec8e6ae19
child 1645 374586978230
--- a/web/__init__.py	Mon May 04 10:52:00 2009 +0200
+++ b/web/__init__.py	Mon May 04 11:47:33 2009 +0200
@@ -7,10 +7,12 @@
 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
 """
 __docformat__ = "restructuredtext en"
+_ = unicode
 
-from cubicweb.web._exceptions import *    
+from simplejson import dumps
 
-_ = unicode
+from cubicweb.web._exceptions import *
+
 
 INTERNAL_FIELD_VALUE = '__cubicweb_internal_field__'
 
@@ -37,3 +39,44 @@
 
 # XXX deprecated
 FACETTES = set()
+
+
+
+def json_dumps(value):
+    if isinstance(value, decimal.Decimal):
+        value = float(value)
+    elif isinstance(value, (date, datetime)):
+        value = value.strftime('%Y-%m-%d %H:%M')
+    elif isinstance(value, timedelta):
+        value = (value.days * 24*60*60) + value.seconds
+    try:
+        return simplejson.dumps(value)
+    except TypeError:
+        return simplejson.dumps(repr(value))
+
+def jsonize(function):
+    def newfunc(*args, **kwargs):
+        return json_dumps(function(*args, **kwargs))
+    return newfunc
+
+def ajax_replace_url(nodeid, rql, vid=None, swap=False, **extraparams):
+    """builds a replacePageChunk-like url
+    >>> ajax_replace_url('foo', 'Person P')
+    "javascript: replacePageChunk('foo', 'Person%20P');"
+    >>> ajax_replace_url('foo', 'Person P', 'oneline')
+    "javascript: replacePageChunk('foo', 'Person%20P', 'oneline');"
+    >>> ajax_replace_url('foo', 'Person P', 'oneline', name='bar', age=12)
+    "javascript: replacePageChunk('foo', 'Person%20P', 'oneline', {'age':12, 'name':'bar'});"
+    >>> ajax_replace_url('foo', 'Person P', name='bar', age=12)
+    "javascript: replacePageChunk('foo', 'Person%20P', 'null', {'age':12, 'name':'bar'});"
+    """
+    params = [repr(nodeid), repr(urlquote(rql))]
+    if extraparams and not vid:
+        params.append("'null'")
+    elif vid:
+        params.append(repr(vid))
+    if extraparams:
+        params.append(json_dumps(extraparams))
+    if swap:
+        params.append('true')
+    return "javascript: replacePageChunk(%s);" % ', '.join(params)