Commits

David Chambers  committed a1c46c8

Added `Document#get`, a factory method which encapsulates the caching logic
previously found in `Category#add_document`. `Document` instances now have a
`lastmod` attribute, obviating the need to cache `os.path.getmtime(filepath)`
and thus greatly simplifying cache lookups: `document = cache.get(cache_key)`
replaces `document, mod_time = cache.get(cache_key, (None, None))`. Existing
`document, mod_time` tuples are ignored if retrieved from the cache.

  • Participants
  • Parent commits 99af5fc

Comments (0)

Files changed (1)

         self.pages.sort(key=lambda page: page.title)
 
     def add_document(self, filepath):
-        if POST_CACHE_SECONDS:
-            cache_key = 'mango:%s' % filepath
-            document, mod_time = cache.get(cache_key, (None, None)) # retrieve Document
-            if document is not None and mod_time == os.path.getmtime(filepath):
-                logger.debug('Document object retrieved from cache: %s' % filepath)
-            else: # modified or not in cache, so create and cache a new Document object
-                document = Document(filepath)
-                cache.set(cache_key, (document, os.path.getmtime(filepath)), POST_CACHE_SECONDS)
-                logger.debug('Document object created and cached: %s' % filepath)
-        else:
-            document = Document(filepath)
+        document = Document.get(filepath)
 
         if document.type == 'page':
             self.pages.append(document)
 
 
 class Document(Resource):
+    @classmethod
+    def get(cls, filepath):
+        if POST_CACHE_SECONDS is 0:
+            return Document(filepath)
+
+        cache_key = 'mango:%s' % filepath
+        lastmod = os.path.getmtime(filepath)
+        document = cache.get(cache_key)
+
+        if isinstance(document, Document) and document.lastmod == lastmod:
+            logger.debug('Document object retrieved from cache: %s' % filepath)
+        else:
+            document = Document(filepath)
+            document.lastmod = lastmod
+            cache.set(cache_key, document, POST_CACHE_SECONDS)
+            logger.debug('Document object created and cached: %s' % filepath)
+
+        return document
+
     def __init__(self, filepath=None, parent=None):
         if parent is None and filepath:
             super(Document, self).__init__(path=filepath)
         self._thread = None
         self._tags = None
 
+        self.lastmod = None
         self.previous = None
         self.next = None