Permalink
Browse files

Resurrecting the smarter logic of the "other" tw encoder. Hurray for …

…git history.
  • Loading branch information...
ralphbean committed May 9, 2012
1 parent 0e775ab commit 1379196d338e801c04080a63843ab138077683b6
Showing with 26 additions and 5 deletions.
  1. +1 −1 tests/test_resources.py
  2. +25 −4 tw2/core/js.py
@@ -295,7 +295,7 @@ def testEncoderDefault(self):
enc = twc.encoder
enc.encode("")
res = enc.default(twr.JSSymbol("X"))
self.assert_(res.startswith("*#*"))
self.assert_(res.startswith("TW2Encoder_unescape_"))
try:
res = enc.default(None)
@@ -7,6 +7,7 @@
as a "bridge" or interface between Python and JavaScript so JS function
**calls** can be generated programatically.
"""
import re
import sys
import logging
@@ -49,6 +50,7 @@ def __init__(self, *args, **kw):
# TODO -- make json encoding pretty-printing configurable
#kw['indent'] = ' '
self.unescape_pattern = re.compile('"TW2Encoder_unescape_([0-9]*)"')
self.pass_through = (_js_call, js_callback, js_symbol, js_function)
super(TWEncoder, self).__init__(*args, **kw)
@@ -57,20 +59,39 @@ def __init__(self, *args, **kw):
def default(self, obj):
if isinstance(obj, self.pass_through):
return self.mark_for_escape(obj)
elif hasattr(obj, 'id'):
result = self.mark_for_escape(obj)
return result
if hasattr(obj, '__json__'):
return obj.__json__()
if hasattr(obj, 'id'):
return str(obj.id)
return super(TWEncoder, self).default(obj)
def encode(self, obj):
self.unescape_symbols = {}
encoded = super(TWEncoder, self).encode(obj)
unescaped = self.unescape_marked(encoded)
self.unescape_symbols = {}
return unescaped
encoded = super(TWEncoder, self).encode(obj)
return self.unescape_marked(encoded)
def mark_for_escape(self, obj):
return '*#*%s*#*' % obj
self.unescape_symbols[id(obj)] = obj
return 'TW2Encoder_unescape_' + str(id(obj))
def unescape_marked(self, encoded):
return encoded.replace('"*#*', '').replace('*#*"', '')
def unescape(match):
obj_id = int(match.group(1))
obj = self.unescape_symbols[obj_id]
return str(obj)
return self.unescape_pattern.sub(unescape, encoded)
encoder = None # This gets reset at the bottom of the file.

0 comments on commit 1379196

Please sign in to comment.