summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlexander Artemenko <svetlyak.40wt@gmail.com>2011-10-16 11:00:06 +0400
committerAlexander Artemenko <svetlyak.40wt@gmail.com>2011-10-16 11:00:06 +0400
commit23ab6c4724cded5dac64c164773b76794ec3b00e (patch)
tree33fe47a9498b6601fb1d84ca6f103a6423f91077
parent32a09ccd6ac26a3cbf4d632871ef383787acbb80 (diff)
downloadtablib-23ab6c4724cded5dac64c164773b76794ec3b00e.tar.gz
Render table in Markdown format on unicode(dataset). Closes #41.
-rw-r--r--tablib/core.py17
-rwxr-xr-xtest_tablib.py16
2 files changed, 33 insertions, 0 deletions
diff --git a/tablib/core.py b/tablib/core.py
index 1bdd49f..80f4418 100644
--- a/tablib/core.py
+++ b/tablib/core.py
@@ -223,6 +223,23 @@ class Dataset(object):
except AttributeError:
return '<dataset object>'
+ def __unicode__(self):
+ result = [self.__headers]
+
+ result.extend(map(unicode, row) for row in self._data)
+
+ # here, we calculate max width for each column
+ lens = (map(len, row) for row in result)
+ field_lens = map(max, zip(*lens))
+
+ # delimiter between header and data
+ result.insert(1, [u'-' * length for length in field_lens])
+
+ format_string = u'|'.join(u'{%s:%s}' % item for item in enumerate(field_lens))
+
+ return u'\n'.join(format_string.format(*row) for row in result)
+
+
# ---------
# Internals
diff --git a/test_tablib.py b/test_tablib.py
index 5455c28..0bfb417 100755
--- a/test_tablib.py
+++ b/test_tablib.py
@@ -649,6 +649,22 @@ class TablibTestCase(unittest.TestCase):
self.assertEquals(self.founders[orig_target_header], data[target_header])
+ def test_unicode_renders_markdown_table(self):
+ # add another entry to test right field width for
+ # integer
+ self.founders.append(('Old', 'Man', 100500))
+
+ self.assertEquals(
+ u"""
+first_name|last_name |gpa
+----------|----------|------
+John |Adams |90
+George |Washington|67
+Thomas |Jefferson |50
+Old |Man |100500
+""".strip(),
+ unicode(self.founders)
+ )
if __name__ == '__main__':