Commits

Anonymous committed ee67e32

tag cloud working

Comments (0)

Files changed (2)

newsmeme/models.py

     :copyright: (c) 2010 by Dan Jacob.
     :license: BSD, see LICENSE for more details.
 """
+import random
 import markdown
 
 from datetime import datetime
               primary_key=True))
 
 
+class TagQuery(BaseQuery):
+
+    def cloud(self):
+
+        tags = self.filter(Tag.num_posts > 0).all()
+
+        if not tags:
+            return []
+
+        max_posts = max(t.num_posts for t in tags)
+        min_posts = min(t.num_posts for t in tags)
+
+        diff = (max_posts - min_posts) / 5.0
+
+        for tag in tags:
+            tag.size = int(tag.num_posts / diff)
+            if tag.size < 1: 
+                tag.size = 1
+
+        random.shuffle(tags)
+
+        return tags
+
+
 class Tag(db.Model):
 
     __tablename__ = "tags"
+    
+    query_class = TagQuery
 
     id = db.Column(db.Integer, primary_key=True)
     slug = db.Column(db.Unicode(80), unique=True)

tests/test_models.py

 
 from tests import TestCase
 
+class TestTags(TestCase):
+
+    def test_empty_tag_cloud(self):
+
+        tags = Tag.query.cloud()
+
+        assert tags == []
+
+    def test_tag_cloud_with_posts(self):
+
+        user = User(username="tester",
+                    email="tester@example.com",
+                    password="test")
+
+        db.session.add(user)
+        db.session.commit()
+        
+        for i in xrange(20):
+            post = Post(author=user,
+                        title="test",
+                        tags = "Music, comedy, IT crowd")
+
+
+            db.session.add(post)
+            db.session.commit()
+
+        for i in xrange(10):
+            post = Post(author=user,
+                        title="test",
+                        tags = "Twitter, YouTube, funny")
+
+            db.session.add(post)
+            db.session.commit()
+
+        post = Post(author=user,
+                    title="test",
+                    tags="Beer, parties, kegs")
+
+        db.session.add(post)
+        db.session.commit()
+
+        assert Tag.query.count() == 9
+
+        tags = Tag.query.cloud()
+
+        for tag in tags:
+
+            if tag.name in ("it crowd", "music", "comedy"):
+                assert tag.size == 5
+
+            elif tag.name in ("twitter", "youtube", "funny"):
+                assert tag.size == 2
+
+            elif tag.name in ("beer", "parties", "kegs"):
+                assert tag.size == 1
+
+
 class TestUser(TestCase):
 
     def test_check_password_if_password_none(self):