]> asedeno.scripts.mit.edu Git - bluechips.git/blob - bluechips/model/types.py
Add some documentation to the Currency type
[bluechips.git] / bluechips / model / types.py
1 """
2 Define special types used in BlueChips
3 """
4
5 import sqlalchemy as sa
6 from bluechips.lib.subclass import SmartSubclass
7
8 class Currency(object):
9     """
10     Store currency values as an integral number of cents
11     """
12     __metaclass__ = SmartSubclass(int)
13     def __init__(self, value):
14         if isinstance(value, str):
15             self.value = int(float(value) * 100)
16         else:
17             self.value = int(value)
18     
19     def __int__(self):
20         """
21         If I don't define this, SmartSubclass will return
22         Currency(int(self.value))
23         """
24         return self.value
25     def __float__(self):
26         """
27         If I don't define this, SmartSubclass will return
28         Currency(float(self.value))
29         """
30         return float(self.value)
31     def __long__(self):
32         """
33         If I don't define this, SmartSubclass will return
34         Currency(long(self.value))
35         """
36         return long(self.value)
37     
38     def __cmp__(self, other):
39         """
40         This is overridden for when validators compare a Currency to
41         ''
42         """
43         if other == '':
44             return 1
45         else:
46             return self.value.__cmp__(int(other))
47     
48     def __mul__(self, other):
49         """
50         If I don't define this, SmartSubclass will convert the other
51         argument to an int
52         """
53         return Currency(self.value * other)
54     def __rmul__(self, other):
55         """
56         If I don't define this, SmartSubclass will convert the other
57         argument to an int
58         """
59         return self.__mul__(other)
60     
61     def __str_no_dollar__(self):
62         """
63         Get to the formatted string without the dollar sign
64         """
65         return str(self)[1:]
66     
67     def __repr__(self):
68         return '%s("%s")' % (self.__class__.__name__, str(self))
69     def __str__(self):
70         sign = '-' if self.value < 0 else ''
71         cents = abs(self.value) % 100
72         dollars = (abs(self.value) - cents) / 100
73         return '$%s%s.%.02d' % (sign, dollars, cents)
74
75 class DBCurrency(sa.types.TypeDecorator):
76     """
77     A type which represents monetary amounts internally as integers.
78     
79     This avoids binary/decimal float conversion issues
80     """
81     
82     impl = sa.types.Integer
83     
84     def process_bind_param(self, value, engine):
85         return int(value)
86     
87     def convert_result_value(self, value, engine):
88         return Currency(value)