-
Notifications
You must be signed in to change notification settings - Fork 5
/
MModel.m
275 lines (226 loc) · 8.96 KB
/
MModel.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
//
// MDictionaryBackedObject.m
// Mib.io
//
// Created by Ben Gotow on 6/7/12.
// Copyright (c) 2012 Foundry376. All rights reserved.
//
#import "MModel.h"
#import "MAPIClient.h"
#import "MModelCollection.h"
#import "NSObject+Properties.h"
#import "NSString+FormatConversion.h"
@implementation MModel
- (id)initWithDictionary:(NSDictionary*)json
{
self = [super init];
if (self) {
[self setup];
[self updateWithResourceJSON: json];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self){
NSDictionary * mapping = [[self class] resourceKeysForPropertyKeys];
NSArray * properties = [mapping allKeys];
_resourcePathOverride = [aDecoder decodeObjectForKey:@"resourcePathOverride"];
[self setup];
[self setEachPropertyInSet:properties withValueProvider:^BOOL(id key, NSObject ** value, NSString * type) {
if (![aDecoder containsValueForKey: key])
return NO;
*value = [aDecoder decodeObjectForKey: key];
return YES;
}];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
NSDictionary * mapping = [[self class] resourceKeysForPropertyKeys];
NSArray * properties = [mapping allKeys];
[self getEachPropertyInSet:properties andInvoke:^(id key, NSString *type, id value) {
if ([value isKindOfClass: [NSCache class]])
return;
if (value == nil)
return;
[aCoder encodeObject:value forKey:key];
}];
if (_resourcePathOverride)
[aCoder encodeObject:_resourcePathOverride forKey: @"resourcePathOverride"];
}
- (void)setup
{
}
- (NSComparisonResult)sort:(MModel*)other
{
return [[self createdAt] compare: [other createdAt]];
}
- (BOOL)isEqual:(id)object
{
return (([object class] == [self class]) && ([[object ID] isEqualToString: [self ID]]));
}
- (BOOL)isSaved
{
return [self ID] != nil;
}
- (BOOL)isUnsaved
{
return [self ID] == nil;
}
- (NSString*)description
{
return [NSString stringWithFormat: @"%@ <%p> - Data: %@", NSStringFromClass([self class]), self, [self resourceJSON]];
}
- (NSString*)resourcePath
{
if (_resourcePathOverride)
return _resourcePathOverride;
NSAssert([self ID], @"MModel does not have a resource path. Add it to a collection before saving it!");
NSAssert(_parent, @"MModel does not have a parent, cannot create it's URL!");
return [[_parent resourcePath] stringByAppendingPathComponent: [self ID]];
}
- (NSMutableDictionary*)resourceJSON
{
NSDictionary * mapping = [[self class] resourceKeysForPropertyKeys];
NSArray * properties = [mapping allKeys];
NSMutableDictionary * json = [NSMutableDictionary dictionary];
[self getEachPropertyInSet:properties andInvoke: ^(id key, NSString * type, id value) {
if ([value isKindOfClass: [MModelCollection class]] || [value isKindOfClass: [MModel class]])
return;
if ([value isKindOfClass: [NSDate class]]) {
if ([[API_TIMESTAMP_FORMAT lowercaseString] isEqualToString: @"u"])
value = [NSString stringWithFormat: @"%.f",[(NSDate*)value timeIntervalSince1970]];
else
value = [NSString stringWithDate: (NSDate*)value format: API_TIMESTAMP_FORMAT];
}
if ([value isKindOfClass: [NSArray class]])
value = [value componentsJoinedByString: @","];
NSString * jsonKey = [mapping objectForKey: key];
if (value)
[json setObject:value forKey:jsonKey];
else
[json setObject:[NSNull null] forKey:jsonKey];
}];
return json;
}
- (void)updateWithResourceJSON:(NSDictionary*)json
{
NSDictionary * mapping = [[self class] resourceKeysForPropertyKeys];
NSArray * properties = [mapping allKeys];
if ([json isKindOfClass: [NSDictionary class]] == NO) {
NSLog(@"updateWithResourceJSON called with json that is not a dictionary");
return;
}
[self setEachPropertyInSet: properties withValueProvider:^BOOL(id key, NSObject ** value, NSString * type) {
NSString * jsonKey = [mapping objectForKey: key];
if (![json objectForKey: jsonKey])
return NO;
if ([type isEqualToString: @"float"]) {
*value = [NSNumber numberWithFloat: [[json objectForKey: jsonKey] floatValue]];
} else if ([type isEqualToString: @"int"]) {
*value = [NSNumber numberWithInt: [[json objectForKey: jsonKey] intValue]];
} else if ([type isEqualToString: @"Tc"]) {
*value = [NSNumber numberWithBool: [[json objectForKey: jsonKey] boolValue]];
} else if ([type isEqualToString: @"T@\"NSDate\""]) {
NSString * timestamp = [json objectForKey: jsonKey];
if ([timestamp isKindOfClass: [NSNumber class]]) {
timestamp = [(NSNumber*)timestamp stringValue];
}
if ([timestamp isKindOfClass: [NSString class]]) {
if ([timestamp hasSuffix: @"Z"])
timestamp = [[timestamp substringToIndex:[timestamp length] - 1] stringByAppendingString:@"-0000"];
if ([[API_TIMESTAMP_FORMAT lowercaseString] isEqualToString: @"u"])
*value = [NSDate dateWithTimeIntervalSince1970: [timestamp intValue]];
else
*value = [timestamp dateValueWithFormat: API_TIMESTAMP_FORMAT];
} else {
*value = nil;
}
} else if ([type isEqualToString: @"T@\"MModelCollection\""]) {
MModelCollection * collection = (MModelCollection *)*value;
[collection modelsFetched:[json objectForKey: jsonKey] replaceExistingContents:YES];
[collection setRefreshDate: [NSDate date]];
} else {
type = [type stringByReplacingOccurrencesOfString:@"T@" withString:@""];
type = [type stringByReplacingOccurrencesOfString:@"\"" withString:@""];
Class klass = NSClassFromString(type);
if ([klass isSubclassOfClass: [MModel class]]) {
id obj = [json objectForKey: jsonKey];
if ([obj isKindOfClass: [NSDictionary class]])
*value = [[klass alloc] initWithDictionary: obj];
else
*value = nil; // could be NSNull, or NSNumber (false)
} else {
*value = [json objectForKey: jsonKey];
}
}
return YES;
}];
[[NSNotificationCenter defaultCenter] postNotificationName:NOTIF_MODEL_CHANGED object:self];
}
- (void)save:(MAPITransactionCallback)callback
{
MAPITransaction * t = [MAPITransaction transactionForPerforming:TRANSACTION_SAVE of:self];
if (callback) [t setCallback: callback];
[[MAPIClient shared] queueAPITransaction: t];
}
- (void)reload:(MAPITransactionCallback)callback
{
[[MAPIClient shared] dictionaryAtPath:[self resourcePath] userTriggered:NO success:^(id responseObject) {
[self updateWithResourceJSON: responseObject];
if (callback) callback(YES);
} failure:^(NSError *err) {
if (callback) callback(NO);
}];
}
# pragma mark Getting and Setting Resource Properties
+ (NSMutableDictionary *)resourceKeysForPropertyKeys
{
return [@{ @"ID": @"id", @"createdAt": @"created_at", @"updatedAt": @"updated_at" } mutableCopy];
}
- (void)getEachPropertyInSet:(NSArray*)properties andInvoke:(void (^)(id key, NSString * type, id value))block
{
for (NSString * key in properties) {
if (![self hasPropertyNamed: key]) {
NSLog(@"No getter available for property %@", key);
return;
}
NSString * type = [NSString stringWithCString:[self typeOfPropertyNamed: key] encoding: NSUTF8StringEncoding];
id val = [self valueForKey: key];
block(key, type, val);
}
}
- (void)setEachPropertyInSet:(NSArray*)properties withValueProvider:(BOOL (^)(id key, NSObject ** value, NSString * type))block
{
for (NSString * key in properties) {
SEL setter = [self setterForPropertyNamed: key];
if (setter == NULL) {
NSLog(@"No setter available for property %@", key);
continue;
}
NSString * type = [NSString stringWithCString:[self typeOfPropertyNamed: key] encoding: NSUTF8StringEncoding];
NSObject * value = [self valueForKey: key];
if (block(key, &value, type)) {
if ([value isKindOfClass: [NSNull class]]) {
if ([type isEqualToString:@"Ti"] || [type isEqualToString:@"Tf"])
[self setValue:[NSNumber numberWithInt: 0] forKey:key];
else if ([type isEqualToString: @"Tc"])
value = [NSNumber numberWithBool: NO];
else
[self setValue:nil forKey:key];
} else {
if ([type isEqualToString: @"T@\"NSString\""] && [value isKindOfClass: [NSNumber class]])
value = [(NSNumber*)value stringValue];
if ([type isEqualToString: @"Tc"]) {
if ([value isKindOfClass: [NSString class]])
value = [NSNumber numberWithChar: [(NSString*)value characterAtIndex: 0]];
}
[self setValue:value forKey:key];
}
}
}
}
@end