]> git.openstreetmap.org Git - osqa.git/blob - forum/settings/base.py
08f3ea8b60ca66504b9eb7477c30f3818356d717
[osqa.git] / forum / settings / base.py
1 import django.dispatch
2 from django.utils.encoding import force_unicode
3
4 class SettingSet(list):
5     def __init__(self, name, title, description, weight=1000, markdown=False):
6         self.name = name
7         self.title = title
8         self.description = description
9         self.weight = weight
10         self.markdown = markdown
11         
12
13 class BaseSetting(object):
14     @classmethod
15     def add_to_class(cls, name):
16         def wrapper(self, *args, **kwargs):
17             return self.value.__getattribute__(name)(*args, **kwargs)
18
19         setattr(cls, name, wrapper)
20
21     def __init__(self, name, default, set=None, field_context=None):
22         self.name = name
23         self.default = default
24         self.field_context = field_context or {}
25
26         if set is not None:
27             if not set.name in Setting.sets:
28                 Setting.sets[set.name] = set
29
30             Setting.sets[set.name].append(self)
31
32     def __unicode__(self):
33         return unicode(self.value)
34
35     @property
36     def value(self):
37         from forum.models import KeyValue
38
39         try:
40             kv = KeyValue.objects.get(key=self.name)
41         except:
42             kv = KeyValue(key=self.name, value=self._parse(self.default))
43             kv.save()
44
45         return kv.value
46
47     def set_value(self, new_value):
48         new_value = self._parse(new_value)
49         self.save(new_value)
50
51     def save(self, value):
52         from forum.models import KeyValue
53
54         try:
55             kv = KeyValue.objects.get(key=self.name)
56         except:
57             kv = KeyValue(key=self.name)
58
59         kv.value = value
60         kv.save()
61
62     def to_default(self):
63         self.set_value(self.default)
64
65     def _parse(self, value):
66         return value
67
68
69 class Setting(object):
70     emulators = {}
71     sets = {}
72
73     def __new__(cls, name, default, set=None, field_context=None):
74         deftype = type(default)
75
76         if deftype in Setting.emulators:
77             emul = Setting.emulators[deftype]
78         else:
79             emul = type(deftype.__name__ + cls.__name__, (BaseSetting,), {})
80             fns = [n for n, f in [(p, getattr(deftype, p)) for p in dir(deftype) if not p in dir(cls)] if callable(f)]
81
82             for n in fns:
83                emul.add_to_class(n)
84
85             Setting.emulators[deftype] = emul
86
87         return emul(name, default, set, field_context)
88
89