1
|
|
|
class MetaCollections(): |
2
|
|
|
def __init__(self): |
3
|
|
|
self._metas = {} |
4
|
|
|
|
5
|
|
|
def reset(self): |
6
|
|
|
self._metas = {} |
7
|
|
|
|
8
|
|
|
def get_collection(self, name): |
9
|
|
|
if name not in self._metas: |
10
|
|
|
self._metas[name] = {} |
11
|
|
|
return self._metas[name] |
12
|
|
|
|
13
|
|
|
def get(self, name, subject, allow_empty=False): |
14
|
|
|
metas = self.get_collection(name) |
15
|
|
|
if subject not in metas and allow_empty: |
16
|
|
|
metas[subject] = [] |
17
|
|
|
return metas[subject] |
18
|
|
|
|
19
|
|
|
def add(self, name, subject, value, assert_not_in=True, allow_multiple=False): |
20
|
|
|
collection = self.get(name, subject, allow_empty=True) |
21
|
|
|
if value in collection: |
22
|
|
|
if assert_not_in: |
23
|
|
|
raise Exception() # TODO: Exception perso |
24
|
|
|
if not allow_multiple: |
25
|
|
|
return |
26
|
|
|
collection.append(value) |
27
|
|
|
|
28
|
|
|
def remove(self, name, subject, value, allow_empty=False, allow_not_in=False): |
29
|
|
|
collection = self.get(name, subject, allow_empty=allow_empty) |
30
|
|
|
try: |
31
|
|
|
collection.remove(value) |
32
|
|
|
except ValueError: |
33
|
|
|
if not allow_not_in: |
34
|
|
|
raise |
35
|
|
|
|
36
|
|
|
def have(self, name, subject, value, allow_empty=False): |
37
|
|
|
collection = self.get(name, subject, allow_empty) |
38
|
|
|
return value in collection |
39
|
|
|
|
40
|
|
|
def unset(self, name, subject, allow_empty=False): |
41
|
|
|
metas = self.get_collection(name) |
42
|
|
|
if subject not in metas and allow_empty: |
43
|
|
|
return |
44
|
|
|
del(metas[subject]) |
45
|
|
|
|
46
|
|
|
def clean(self, name): |
47
|
|
|
metas = self.get_collection(name) |
48
|
|
|
cleaned_metas = dict(metas) |
49
|
|
|
for meta in metas: |
50
|
|
|
if not len(metas[meta]): |
51
|
|
|
del (cleaned_metas[meta]) |
52
|
|
|
self._metas[name] = cleaned_metas |
53
|
|
|
|