X-Git-Url: http://git.veekun.com/zzz-pokedex.git/blobdiff_plain/492c9c72081add3b6ebfe36743906e6c6f82ce92..93be19674c4072725be9aa4eac890931c8b0e294:/pokedex/db/markdown.py?ds=sidebyside diff --git a/pokedex/db/markdown.py b/pokedex/db/markdown.py index 0bc6971..257c8de 100644 --- a/pokedex/db/markdown.py +++ b/pokedex/db/markdown.py @@ -56,44 +56,45 @@ class MarkdownString(object): """ return self.source_text +def _markdownify_effect_text(move, effect_text): + effect_text = effect_text.replace( + u'$effect_chance', + unicode(move.effect_chance), + ) -class _MoveEffects(object): - def __init__(self, effect_column, move): - self.effect_column = effect_column - self.move = move - - def __contains__(self, lang): - return lang in self.move.move_effect.prose + return MarkdownString(effect_text) - def __getitem__(self, lang): - try: - effect_text = getattr(self.move.move_effect.prose[lang], self.effect_column) - except AttributeError: - return None - effect_text = effect_text.replace( - u'$effect_chance', - unicode(self.move.effect_chance), - ) - - return MarkdownString(effect_text) - -class MoveEffectsProperty(object): +class MoveEffectProperty(object): """Property that wraps move effects. Used like this: - MoveClass.effects = MoveEffectProperty('effect') + MoveClass.effect = MoveEffectProperty('effect') - some_move.effects[lang] # returns a MarkdownString - some_move.effects[lang].as_html # returns a chunk of HTML + some_move.effect # returns a MarkdownString + some_move.effect.as_html # returns a chunk of HTML This class also performs simple substitution on the effect, replacing `$effect_chance` with the move's actual effect chance. + + Use `MoveEffectPropertyMap` for dict-like association proxies. """ def __init__(self, effect_column): self.effect_column = effect_column - def __get__(self, move, move_class): - return _MoveEffects(self.effect_column, move) + def __get__(self, obj, cls): + prop = getattr(obj.move_effect, self.effect_column) + return _markdownify_effect_text(obj, prop) + +class MoveEffectPropertyMap(MoveEffectProperty): + """Similar to `MoveEffectProperty`, but works on dict-like association + proxies. + """ + def __get__(self, obj, cls): + prop = getattr(obj.move_effect, self.effect_column) + newdict = dict(prop) + for key in newdict: + newdict[key] = _markdownify_effect_text(obj, newdict[key]) + return newdict class MarkdownColumn(sqlalchemy.types.TypeDecorator): """Generic SQLAlchemy column type for Markdown text. @@ -105,6 +106,9 @@ class MarkdownColumn(sqlalchemy.types.TypeDecorator): impl = sqlalchemy.types.Unicode def process_bind_param(self, value, dialect): + if value is None: + return None + if not isinstance(value, basestring): # Can't assign, e.g., MarkdownString objects yet raise NotImplementedError @@ -112,4 +116,7 @@ class MarkdownColumn(sqlalchemy.types.TypeDecorator): return unicode(value) def process_result_value(self, value, dialect): + if value is None: + return None + return MarkdownString(value)