Skip to content

Commit

Permalink
add basic type coercion for comparisons
Browse files Browse the repository at this point in the history
  • Loading branch information
mahmoud committed Apr 9, 2013
1 parent c7ed3d7 commit 105334b
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions ashes.py
Original file line number Diff line number Diff line change
Expand Up @@ -784,6 +784,10 @@ def _literal(self, node):
#########
# Runtime
#########

# Escapes/filters


def escape_html(text):
text = unicode(text)
# TODO: dust.js doesn't use this, but maybe we should: .replace("'", '&squot;')
Expand Down Expand Up @@ -871,14 +875,13 @@ def _do_compare(chunk, context, bodies, params, cmp_op):
body = bodies['block']
key = params['key']
value = params['value']
cmp_type = params.get('type', 'repr')
# TODO: is repr() a good choice?
# TODO: type aliases
typestr = params.get('type', 'string')
except KeyError:
return chunk
cmp_type # TODO: coerce
rkey = _resolve_value(key, chunk, context)
rvalue = _resolve_value(value, chunk, context)
crkey, crvalue = _coerce(rkey, typestr), _coerce(rvalue, typestr)
# TODO: False on TypeError/type mismatch
if cmp_op(rkey, rvalue):
return chunk.render(body, context)
elif 'else' in bodies:
Expand All @@ -895,6 +898,24 @@ def _resolve_value(item, chunk, context):
return None


_COERCE_MAP = {
'number': float,
'string': unicode, # TODO
'boolean': bool, # TODO
} # Not implemented: date, context


def _coerce(value, typestr):
coerce_func = _COERCE_MAP.get(typestr.lower())
if not coerce_func:
return value
try:
cv = coerce_func(value)
except (TypeError, ValueError):
return value
return cv


def _make_compare_helpers():
from functools import partial
from operator import eq, ne, lt, le, gt, ge
Expand All @@ -913,6 +934,8 @@ def _make_compare_helpers():
'size': size_helper}
DEFAULT_HELPERS.update(_make_compare_helpers())

# Actual runtime objects


class Context(object):
def __init__(self, env, stack, global_vars=None, blocks=None):
Expand Down

0 comments on commit 105334b

Please sign in to comment.