From 949ff883ea83d71ad382e547135686768be5501a Mon Sep 17 00:00:00 2001 From: Petr Viktorin Date: Sun, 12 Feb 2012 22:43:59 +0100 Subject: [PATCH] Autodoc for backrefs --- pokedex/db/tables.py | 23 +++++++++++++++++++---- pokedex/doc/tabledoc.py | 10 ++++++++-- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/pokedex/db/tables.py b/pokedex/db/tables.py index c36b8a6..57ca1bd 100644 --- a/pokedex/db/tables.py +++ b/pokedex/db/tables.py @@ -1407,9 +1407,9 @@ class PokemonSpecies(TableBase): add_relationship('parent_species', PokemonSpecies, primaryjoin=PokemonSpecies.evolves_from_species_id==PokemonSpecies.id, remote_side=[PokemonSpecies.id], - backref='child_species', - info=dict( - description=u"The species from which this one evolves")) + backref=backref('child_species', + info=dict(description=u"The species to which this one evolves")), + info=dict(description=u"The species from which this one evolves")) add_relationship('evolutions', PokemonEvolution, primaryjoin=PokemonSpecies.id==PokemonEvolution.evolved_species_id, backref=backref('evolved_species', @@ -1682,12 +1682,27 @@ def add_relationships(): def add_relationship(name, argument, secondary=None, **kwargs): cls.relationship_info.setdefault('_order', []) cls.relationship_info['_order'].append(name) - cls.relationship_info[name] = kwargs.pop('info', {}) + cls.relationship_info[name] = info = kwargs.pop('info', {}) cls.relationship_info[name].update(kwargs) cls.relationship_info[name].update(dict( type='relationship', argument=argument, secondary=secondary)) + the_backref = kwargs.get('backref') + if isinstance(the_backref, basestring): + the_backref = backref(the_backref) + if the_backref: + # XXX: This line exploits a SQLA implementation detail, + # after all relationships are converted we should make our + # own backref wrapper with known semantics. + backref_name, backref_kwargs = the_backref + + backref_info = dict( + type='backref', + argument=cls, + secondary=secondary) + backref_info.update(backref_kwargs.pop('info', {})) + argument.relationship_info[backref_name] = backref_info setattr(cls, name, relationship(argument, secondary=secondary, **kwargs)) add_relationships(add_relationship=add_relationship) diff --git a/pokedex/doc/tabledoc.py b/pokedex/doc/tabledoc.py index 74287ea..ee92040 100644 --- a/pokedex/doc/tabledoc.py +++ b/pokedex/doc/tabledoc.py @@ -194,8 +194,14 @@ def generate_strings(cls, remaining_attrs): @with_header(u'Relationships') def generate_relationships(cls, remaining_attrs): - for rel_name in [c for c in cls.relationship_info.get('_order', []) - if c in remaining_attrs]: + order = cls.relationship_info.get('_order', []) + def sort_key((key, value)): + try: + return 0, order.index(key) + except ValueError: + return 1, key + infos = sorted(cls.relationship_info.items(), key=sort_key) + for rel_name, info in infos: if rel_name in remaining_attrs: info = cls.relationship_info.get(rel_name) yield u'%s.\ **%s**' % (cls.__name__, rel_name)