changeset 67:fdb77c57bd22

make sort formatter more extensible and add a random method
author Jeff Hammel <jhammel@mozilla.com>
date Fri, 18 Nov 2011 22:34:08 -0800
parents 5d34e9d14666
children 4094bee13154
files decoupage/formatters.py setup.py
diffstat 2 files changed, 21 insertions(+), 7 deletions(-) [+]
line wrap: on
line diff
--- a/decoupage/formatters.py	Thu Oct 27 21:14:41 2011 -0700
+++ b/decoupage/formatters.py	Fri Nov 18 22:34:08 2011 -0800
@@ -1,5 +1,6 @@
 #!/usr/bin/env python
 
+import random
 import sys
 from fnmatch import fnmatch
 from pkg_resources import iter_entry_points
@@ -79,22 +80,35 @@
                     _files.append(f)
         data['files'] = _files
         
-class Sort(object):
+class Sort(FormatterBase):
     """
     determines how to sort the files in a directory; 
     right now only by case-insensitive alphabetically
     * reverse : reverse the order of the sorting
     """
+    defaults = {'order': 'name'}
+    
     def __init__(self, pattern):
-        self.args = [i.strip() for i in pattern.split(',')]
+        FormatterBase.__init__(self, pattern)
+        self.orders = {'name': self.name,
+                       'random': self.random,
+                       }
     
     def __call__(self, request, data):
 
-        data['files'] = sorted(data['files'], key=lambda x: x['name'].lower())
+        sort = self.orders.get(request.GET.get('order', self.order), self.name)
+        data['files'] = sort(data['files'])
 
         if 'reverse' in self.args:
             data['files'] = list(reversed(data['files']))
-    
+
+    def name(self, files):
+        return sorted(files, key=lambda x: x['name'].lower())
+
+    def random(self, files):
+        random.shuffle(files)
+        return files
+
 
 class Order(object):
     """
@@ -187,8 +201,8 @@
                 links = links.split(self.separator)
                 assert min(['=' in link for link in links])
                 links = [ link.split('=', 1) for link in links ]
-                f['links'] = [ { 'text': text, 'link': link }
-                             for text, link in links ]
+                f['links'] = [{ 'text': text, 'link': link }
+                              for text, link in links]
 
 
 class Up(object):
--- a/setup.py	Thu Oct 27 21:14:41 2011 -0700
+++ b/setup.py	Fri Nov 18 22:34:08 2011 -0800
@@ -6,7 +6,7 @@
 except IOError:
     description = ''
 
-version = '0.10.2'
+version = '0.10.3'
 
 setup(name='decoupage',
       version=version,