-
Notifications
You must be signed in to change notification settings - Fork 9
/
ActiveRecord.m
1101 lines (712 loc) · 33.1 KB
/
ActiveRecord.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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ActiveRecord
// Shopify_Mobile
//
// Created by Matthew Newberry on 7/22/10.
// Copyright 2010 Shopify. All rights reserved.
//
#import "ActiveRecord.h"
#import "ObjectiveRecord+Utilities.h"
#import "ActiveRequest.h"
#import "GTMNSString+HTML.h"
@implementation ActiveRecord : NSManagedObject
@synthesize delegate = _delegate;
@synthesize remoteDidFinishSelector = _remoteDidFinishSelector;
@synthesize remoteDidFailSelector = _remoteDidFailSelector;
#pragma mark -
#pragma mark Utilities
+ (void) save{
[[self activeManager].managedObjectContext save];
}
- (ActiveRecord *) save{
[[self class] save];
return self;
}
+ (ActiveManager *) activeManager{
ActiveManager *manager = [ActiveManager shared];
[manager.defaultDateParser setDateFormat:[self dateFormat]];
return manager;
}
+ (NSManagedObjectContext *) managedObjectContext {
return [[self activeManager] managedObjectContext];
}
+ (NSString *) entityName {
return [self entityName:YES];
}
+ (NSString *) entityName: (BOOL) removePrefix{
NSMutableString *name = [NSMutableString stringWithString:$S(@"%@", self)];
if([[self classPrefix] length] > 0 && removePrefix)
[name replaceOccurrencesOfString:[self classPrefix] withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [[self classPrefix] length])];
if(![self shouldParseEntityNameFromRelationships] || ![self hasRelationships])
return name;
NSMutableString *tempName = [NSMutableString stringWithString:name];
for(NSString *key in [self relationshipsByName]){
NSRange search = [name rangeOfString:key options:NSCaseInsensitiveSearch];
if(search.location != NSNotFound){
[tempName deleteCharactersInRange:search];
}
}
return tempName;
}
+ (NSEntityDescription *) entityDescription{
return [NSEntityDescription entityForName:$S(@"%@", self) inManagedObjectContext:[self managedObjectContext]];
}
- (NSMutableDictionary *) properties {
return [self properties:nil withoutObjects:nil];
}
- (NSMutableDictionary *) properties:(NSDictionary *)options {
return [self properties:options withoutObjects:nil];
}
- (NSMutableDictionary *) properties:(NSDictionary *)options withoutObjects:(NSMutableArray *)withouts {
NSArray *only = [options objectForKey:@"$only"];
NSArray *except = [options objectForKey:@"$except"];
BOOL relationships = [options objectForKey:@"$relationships"] == nil ? YES : [[options objectForKey:@"$relationships"] boolValue];
BOOL serializeDates = [[options objectForKey:@"$serializeDates"] boolValue];
if (withouts == nil)
withouts = [NSMutableArray array];
[withouts addObject:self];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSPropertyDescription *prop in [[[self class] entityDescription] properties]) {
NSString *key = prop.name;
if ((only == nil || [only containsObject:key]) && (except == nil || ![except containsObject:key])) {
id value = [self valueForKey:key];
if (value == nil)
value = [NSNull null];
// For attributes, simply set the value
if ([prop isKindOfClass:[NSAttributeDescription class]]) {
// Serialize dates if serializeDates is set
if ([value isKindOfClass:[NSDate class]] && serializeDates)
value = [[[self class] activeManager].defaultDateParser stringFromDate:value];
[dict setObject:value forKey:key];
}
else if(relationships){
NSRelationshipDescription *rel = (NSRelationshipDescription *)prop;
if ([rel isToMany]) {
NSSet *relResources = value;
NSMutableArray *relArray = [NSMutableArray arrayWithCapacity:[relResources count]];
for (ActiveRecord *resource in relResources) {
// Only add objects which are not part of the withouts array
// (most importantly, ignore objects that have been previously added)
if (![withouts containsObject:resource])
[relArray addObject:[resource properties:options withoutObjects:withouts]];
}
[dict setObject:relArray forKey:key];
}
else {
if (![withouts containsObject:value])
[dict setObject:value forKey:key];
}
}
}
}
return dict;
}
+ (NSDictionary *) relationshipsByName {
NSDictionary *rels = [[[self activeManager] modelRelationships] objectForKey:self];
if (rels == nil) {
rels = [[self entityDescription] relationshipsByName];
[[[self activeManager] modelRelationships] setObject:rels forKey:self];
}
return rels;
}
+ (BOOL) hasRelationships {
return [[self relationshipsByName] count] > 0;
}
+ (NSDictionary *) attributesByName {
NSDictionary *attr = [[[self activeManager] modelAttributes] objectForKey:self];
if (attr == nil) {
attr = [[self entityDescription] attributesByName];
[[[self activeManager] modelAttributes] setObject:attr forKey:self];
}
return attr;
}
+ (NSDictionary *) propertiesByName {
NSDictionary *props = [[[self activeManager] modelProperties] objectForKey:self];
if (props == nil) {
props = [[self entityDescription] propertiesByName];
[[[self activeManager] modelProperties] setObject:props forKey:self];
}
return props;
}
+ (NSPropertyDescription *) propertyDescriptionForField:(NSString *)field inModel:(Class)modelClass {
return [[modelClass propertiesByName] objectForKey:field];
}
+ (NSPropertyDescription *) propertyDescriptionForField:(NSString *)field {
return [self propertyDescriptionForField:field inModel:self];
}
+ (NSString *) localNameForRemoteField:(NSString *)name {
return name;
}
+ (NSString *) remoteNameForLocalField:(NSString *)name {
return name;
}
#pragma mark -
#pragma mark Finding
+ (NSArray *) all{
ActiveResult *result = [self find:nil];
return [NSArray arrayWithArray:[result objects]];
}
+ (id) first{
ActiveResult *result = [self find:nil sortBy:nil limit:1 fields:nil];
return [result count] > 0 ? [result object] : nil;
}
+ (id) last{
NSRange sortRange = [[[self defaultSort] lowercaseString] rangeOfString:@"desc"];
NSString *sortDir = sortRange.location == NSNotFound ? @"desc" : @"asc";
ActiveResult *result = [self find:nil sortBy:[[self defaultSort] stringByReplacingCharactersInRange:sortRange withString:sortDir]];
return [result object];
}
+ (BOOL) exists:(NSNumber *)itemID{
return [self findByID:itemID] == nil ? NO : YES;
}
+ (id) findByID:(NSNumber *) itemID{
return [self findByID:itemID moc:[self managedObjectContext]];
}
+ (id) findByID:(NSNumber *)itemID moc:(NSManagedObjectContext *)moc{
if([self propertyDescriptionForField:[self localIDField]] == nil)
return nil;
if(!moc)
moc = [self managedObjectContext];
if(![[self propertiesByName] objectForKey:[self localIDField]])
return nil;
ActiveResult *result = [self find:$P($S(@"%@ = %i", [self localIDField], [itemID intValue])) sortBy:nil limit:1 fields:$A([self localIDField]) moc:moc];
return [result object];
}
+ (ActiveResult *) find:(id) query{
return [self find:query sortBy:nil limit:0 fields:nil];
}
+ (ActiveResult *) find:(id) query sortBy:(NSString *)sortBy{
return [self find:query sortBy:sortBy limit:0 fields:nil];
}
+ (ActiveResult *) find:(id) query limit:(int) limit{
return [self find:query sortBy:nil limit:limit fields:nil];
}
+ (ActiveResult *) find:(id) query sortBy:(NSString *)sortBy limit:(int)limit{
return [self find:query sortBy:sortBy limit:limit fields:nil];
}
+ (ActiveResult *) find:(id) query sortBy:(NSString *)sortBy limit:(int)limit fields:(NSArray *)fields{
return [self find:query sortBy:sortBy limit:limit fields:fields moc:[self managedObjectContext]];
}
+ (ActiveResult *) find:(id) query sortBy:(NSString *)sortBy limit:(int)limit fields:(NSArray *)fields moc:(NSManagedObjectContext *)moc{
NSFetchRequest *fetch = [self fetchRequest];
[fetch setEntity:[self entityDescription]];
[fetch setPredicate:[ActiveSupport predicateFromObject:query]];
[fetch setPropertiesToFetch:fields];
[fetch setFetchBatchSize:20];
if(sortBy != nil)
[fetch setSortDescriptors:[ActiveSupport sortDescriptorsFromString:sortBy]];
if(limit > 0)
[fetch setFetchLimit:limit];
NSError *error;
if(!moc)
moc = [self managedObjectContext];
NSArray *results = [moc executeFetchRequest:fetch error:&error];
ActiveResult *result = [[[ActiveResult alloc] initWithResults:results] autorelease];
return result;
}
#pragma mark -
#pragma mark Utilities
+ (NSFetchRequest *) fetchRequest{
NSFetchRequest *fetch = [[[NSFetchRequest alloc] init] autorelease];
[fetch setEntity:[self entityDescription]];
[fetch setSortDescriptors:[ActiveSupport sortDescriptorsFromString:[self defaultSort]]];
return fetch;
}
+ (int) count{
return [self count:nil];
}
+ (int) count:(NSPredicate *) predicate{
NSFetchRequest *fetch = [self fetchRequest];
[fetch setPredicate:predicate];
return [[self managedObjectContext] countForFetchRequest:fetch error:nil];
}
+ (NSNumber *) sum:(NSString *)property{
ActiveResult *result = [self find:nil sortBy:nil limit:0 fields:$A(property)];
return [[result objects] valueForKeyPath:$S(@"@sum.%@", property)];
}
+ (NSNumber *) minimum:(NSString *)property{
ActiveResult *result = [self find:nil sortBy:nil limit:0 fields:$A(property)];
return [[result objects] valueForKeyPath:$S(@"@min.%@", property)];
}
+ (NSNumber *) maximum:(NSString *)property{
ActiveResult *result = [self find:nil sortBy:nil limit:0 fields:$A(property)];
return [[result objects] valueForKeyPath:$S(@"@max.%@", property)];
}
+ (NSNumber *) average:(NSString *)property{
ActiveResult *result = [self find:nil sortBy:nil limit:0 fields:$A(property)];
return [[result objects] valueForKeyPath:$S(@"@avg.%@", property)];
}
#pragma mark -
#pragma mark Create / Update
- (NSDictionary *) map{
// Subclass to map fields
return [NSDictionary dictionary];
}
+ (id) blank{
return [self create:nil];
}
+ (id) create:(id)parameters {
return [self create:parameters withOptions:[self defaultCreateOptions]];
}
+ (id) create:(id)parameters withOptions:(NSDictionary *)options {
if ([parameters isKindOfClass:[NSArray class]]) {
NSMutableArray *resources = [NSMutableArray arrayWithCapacity:[parameters count]];
for (id item in parameters)
[resources addObject:[self create:item withOptions:options]];
return resources;
}
else {
ActiveRecord *resource = [[self alloc] initWithEntity:[self entityDescription]
insertIntoManagedObjectContext:[ActiveManager shared].managedObjectContext];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSDictionary *map = [resource map];
for(NSString *key in [parameters keyEnumerator]){
NSString *mappedKey = [[map allKeys] indexOfObject:key] == NSNotFound ? key : [map objectForKey:key];
[dict setObject:[parameters objectForKey:key] forKey:[mappedKey stringByReplacingOccurrencesOfString:@"-" withString:@"_"]];
}
[resource update:dict withOptions:options];
[resource willCreate:options data:dict];
if ([[self class] activeManager].logLevel > 1) {
NSLog(@"Created new %@", self);
if ([[self class] activeManager].logLevel > 4)
NSLog(@"=> %@", resource);
}
SEL createdAtSel = NSSelectorFromString([self createdAtField]);
if ([resource respondsToSelector:createdAtSel] && [resource valueForKey:[self createdAtField]] == nil)
[resource setValue:[NSDate date] forKey:[self createdAtField]];
//[resource didCreate:options data:dict];
return [resource autorelease];
}
}
+ (id) build:(id)parameters {
return [self build:parameters withOptions:[self defaultCreateOptions]];
}
+ (id) build:(id)parameters withOptions:(NSDictionary *)options {
id resource;
if ([parameters isKindOfClass:self])
return parameters;
else if ([parameters isKindOfClass:[NSArray class]]) {
NSMutableArray *resources = [NSMutableArray arrayWithCapacity:[parameters count]];
for (id item in parameters){
[resources addObject:[self build:item withOptions:options]];
}
return resources;
}
else if ([parameters isKindOfClass:[NSDictionary class]]) {
id resourceId = [parameters objectForKey:[self remoteIDField]];
if (resourceId != nil && [self exists:$I([resourceId intValue])]){
NSManagedObjectContext *moc = [options objectForKey:@"moc"] ? [options objectForKey:@"moc"] : [self managedObjectContext];
resource = [self findByID:$I([resourceId intValue]) moc:moc];
[resource update:parameters withOptions:options];
}
else
resource = [self create:parameters withOptions:options];
}
return resource;
}
- (ActiveRecord *) threadSafe{
return (ActiveRecord *) [[ActiveManager shared].managedObjectContext existingObjectWithID:[self objectID] error:nil];
}
- (id) update:(NSDictionary *)data{
return [self update:data withOptions:[[self class] defaultUpdateOptions]];
}
- (id) update:(NSDictionary *) data withOptions:(NSDictionary *) options{
ActiveRecord *threadSafeSelf = [self threadSafe];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSDictionary *map = [threadSafeSelf map];
for(NSString *key in [data keyEnumerator]){
NSString *mappedKey = [[map allKeys] indexOfObject:key] == NSNotFound ? key : [map objectForKey:key];
[dict setObject:[data objectForKey:key] forKey:[mappedKey stringByReplacingOccurrencesOfString:@"-" withString:@"_"]];
}
//[threadSafeSelf willUpdate:options data:dict];
for (NSString *field in [dict allKeys]) {
NSString *localField = nil;
if ([field isEqualToString:[[threadSafeSelf class] remoteIDField]])
localField = [[threadSafeSelf class] localIDField];
else
localField = [[threadSafeSelf class] localNameForRemoteField:field];
NSPropertyDescription *propertyDescription = [[threadSafeSelf class] propertyDescriptionForField:localField inModel:[threadSafeSelf class]];
if (propertyDescription != nil) {
id value = [dict objectForKey:field];
// If property is a relationship, do some cascading object creation/updation
if ([propertyDescription isKindOfClass:[NSRelationshipDescription class]]) {
// Get relationship class from core data info
NSRelationshipDescription *relationshipDescription = (NSRelationshipDescription *)propertyDescription;
Class relationshipClass = NSClassFromString([[relationshipDescription destinationEntity] managedObjectClassName]);
id newRelatedResources;
id existingRelatedResources = [threadSafeSelf valueForKey:localField];
// ===== Get related resources from value ===== //
NSDictionary *relationshipOptions = [options objectForKey:relationshipClass];
// If the value is a dictionary or array, use it to create or update an resource
if ([value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSArray class]]) {
newRelatedResources = [relationshipClass build:value withOptions:options];
if ([newRelatedResources isKindOfClass:[NSArray class]])
newRelatedResources = [NSMutableSet setWithArray:newRelatedResources];
}
// Otherwise, if the value is a resource itself, use it directly
else if ([value isKindOfClass:relationshipClass])
newRelatedResources = value;
else if ([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSNumber class]]){
newRelatedResources = [relationshipClass findByID:$I([value intValue])];
[threadSafeSelf setValue:newRelatedResources forKey:localField];
continue;
}
// ===== Apply related resources to self ===== //
NSString *rule = [relationshipOptions objectForKey:@"rule"] ? [relationshipOptions objectForKey:@"rule"] : @"append";
// To-many relationships
if ([relationshipDescription isToMany]) {
// If rule is to add, append new objects to existing
if ([rule isEqualToString:@"append"])
newRelatedResources = [existingRelatedResources setByAddingObjectsFromSet:newRelatedResources];
// If relationship rule is destroy, destroy all old resources that aren't in the new set
else if ([rule isEqualToString:@"destroy"]) {
NSSet *danglers = [existingRelatedResources difference:newRelatedResources];
for (id dangler in danglers)
[dangler remove];
}
// Default action is to replace the set with no further reprecussions (old resources will still persist)
[threadSafeSelf setValue:newRelatedResources forKey:localField];
}
// Singular relationships
else {
// Only process if the new value is different from the current value
if (![newRelatedResources isEqual:existingRelatedResources]) {
// Set new value
[threadSafeSelf setValue:newRelatedResources forKey:localField];
// If relationship rule is destroy, get rid of the old resource
if ([rule isEqualToString:@"destroy"])
[existingRelatedResources remove];
}
}
}
else if ([propertyDescription isKindOfClass:[NSAttributeDescription class]]) {
if ([value isEqual:[NSNull null]])
[threadSafeSelf setValue:nil forKey:localField];
else {
switch ([(NSAttributeDescription *)propertyDescription attributeType]) {
case NSDateAttributeType:
if ([value isKindOfClass:[NSString class]]){
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:[[threadSafeSelf class] dateFormat]];
[threadSafeSelf setValue:[formatter dateFromString:[threadSafeSelf dateFormatPreprocessor:value]] forKey:localField];
[formatter release];
}
break;
case NSInteger16AttributeType:
case NSInteger32AttributeType:
case NSInteger64AttributeType:
if(![value isKindOfClass:[NSNumber class]])
[threadSafeSelf setValue:$I([value intValue]) forKey:localField];
else
[threadSafeSelf setValue:value forKey:localField];
break;
case NSFloatAttributeType:
case NSDecimalAttributeType:
[threadSafeSelf setValue:$F([value floatValue]) forKey:localField];
break;
case NSDoubleAttributeType:
[threadSafeSelf setValue:[NSNumber numberWithDouble:[value doubleValue]] forKey:localField];
break;
case NSBooleanAttributeType:
[threadSafeSelf setValue:[NSNumber numberWithBool:[value boolValue]] forKey:localField];
break;
case NSStringAttributeType:
if([value isKindOfClass:[NSString class]])
[threadSafeSelf setValue:[value unescapeFromHTML] forKey:localField];
else
[threadSafeSelf setValue:[[[self class] activeManager].defaultNumberFormatter stringFromNumber:value] forKey:localField];
break;
}
}
}
}
}
[threadSafeSelf didUpdate:options data:dict];
return threadSafeSelf;
}
+ (id) update:(NSDictionary *)data predicate:(NSPredicate *)predicate{
ActiveResult *results = [self find:predicate];
for(id row in [results objects]){
[row update:data];
}
return self;
}
- (BOOL) shouldUpdateWith:(NSDictionary *)dict {
SEL updatedAtSel = NSSelectorFromString([[self class] updatedAtField]);
if ([self respondsToSelector:updatedAtSel]) {
NSDate *updatedAt = (NSDate *)[self performSelector:updatedAtSel];
if (updatedAt != nil) {
NSString *dictUpdatedAtString = [dict objectForKey:[[self class] updatedAtField]];
if (dictUpdatedAtString != nil) {
NSDate *dictUpdatedAt = [[[self class] activeManager].defaultDateParser dateFromString:[self dateFormatPreprocessor:dictUpdatedAtString]];
if (updatedAt != nil) {
return [updatedAt compare:dictUpdatedAt] == NSOrderedAscending;
}
}
}
}
return YES;
}
#pragma mark -
#pragma mark Remove
+ (void) removeAll{
[self remove:nil];
//[self save];
}
+ (void) remove:(NSPredicate *) predicate{
ActiveResult *results = [self find:predicate];
for(id row in [results objects]){
[row remove];
}
}
- (void) remove{
[[self managedObjectContext] deleteObject:self];
}
#pragma mark -
#pragma mark Remote
+ (NSString *) remoteURLForAction:(Action)action{
return [self remoteURLForAction:action withContentFormat:YES];
}
+ (NSString *) remoteURLForAction:(Action)action withContentFormat:(BOOL) withContentFormat{
NSMutableArray *pieces = [NSMutableArray array];
[pieces addObject:$S(@"%@", [[[[self entityName] lowercaseString] underscore] pluralForm])];
if(withContentFormat)
[pieces addObject:$S(@"%@", [self activeManager].remoteContentFormat)];
return [pieces componentsJoinedByString:@"."];
}
- (NSString *) resourceURLForAction:(Action)action{
return [self resourceURLForAction:action withContentFormat:YES];
}
- (NSString *) resourceURLForAction:(Action)action withContentFormat:(BOOL) withContentFormat{
NSMutableArray *pieces = [NSMutableArray arrayWithObject:[[$S(@"%@", [self class]) pluralForm] lowercaseString]];
[pieces addObject:$S(@"%i", [[self valueForKey:[[self class] localIDField]] intValue])];
NSMutableString *name = [NSMutableString stringWithString:[pieces objectAtIndex:0]];
if(![[self class] shouldParseEntityNameFromRelationships] || ![[self class] hasRelationships])
return [pieces componentsJoinedByString:@"/"];
for(NSString *key in [[self class] relationshipsByName]){
NSRange search = [[pieces objectAtIndex:0] rangeOfString:key options:NSCaseInsensitiveSearch];
if(search.location != NSNotFound){
[pieces insertObject:[[key pluralForm] lowercaseString] atIndex:0];
[name deleteCharactersInRange:search];
[pieces replaceObjectAtIndex:1 withObject:name];
ActiveRecord *relationship = (ActiveRecord *) [self valueForKey:key];
NSString *relatedId = [[relationship valueForKey:[[relationship class] localIDField]] stringValue];
if(relatedId)
[pieces insertObject:relatedId atIndex:1];
}
}
if(withContentFormat)
[pieces replaceObjectAtIndex:[pieces count]-1 withObject:$S(@"%@.%@", [pieces lastObject], [[self class] activeManager].remoteContentFormat)];
return [pieces componentsJoinedByString:@"/"];
}
- (NSString *) relationshipURL:(NSString *) relationship forAction:(Action) action{
return [self relationshipURL:relationship forAction:action withContentFormat:YES];
}
- (NSString *) relationshipURL:(NSString *)relationship forAction:(Action)action withContentFormat:(BOOL) withContentFormat{
NSMutableArray *pieces = [NSMutableArray array];
[pieces addObject:[[[[[self class] entityName] lowercaseString] underscore] pluralForm]];
[pieces addObject:$S(@"%i", [[self valueForKey:[[self class] localIDField]] intValue])];
[pieces addObject:relationship];
if(withContentFormat)
[pieces replaceObjectAtIndex:[pieces count]-1 withObject:$S(@"%@.%@", [pieces lastObject], [[self class] activeManager].remoteContentFormat)];
return [pieces componentsJoinedByString:@"/"];
}
- (ActiveResult *) fetch{
ActiveRequest *request = [self requestForFetch];
return [[[self class] activeManager] addSyncronousRequest:request];
}
- (void) fetchProperties:(NSDictionary *) properties{
ActiveRequest *request = [self requestForFetch];
[request addParameters:properties];
[[[self class] activeManager] addRequest:request didParseObjectBlock:nil didFinishBlock:nil didFailBlock:nil];
}
- (void) fetch:(id) delegate didFinishSelector:(SEL) didFinishSelector didFailSelector:(SEL)didFailSelector{
[self fetchRelationship:nil delegate:delegate didFinishSelector:didFinishSelector didFailSelector:didFailSelector];
}
- (void) fetch:(ActiveConnectionBlock)didFinishBlock didFailBlock:(ActiveConnectionBlock)didFailBlock{
[self fetchRelationship:nil didFinishBlock:didFinishBlock didFailBlock:didFailBlock];
}
- (void) fetchRelationship:(NSString *) relationship delegate:(id) delegate didFinishSelector:(SEL) didFinishSelector didFailSelector:(SEL)didFailSelector{
ActiveRequest *request = [self requestForFetch];
if(relationship)
request.urlPath = [self relationshipURL:relationship forAction:Read];
request.didFinishSelector = didFinishSelector;
request.didFailSelector = didFailSelector;
[[[self class] activeManager] addRequest:request];
}
- (void) fetchRelationship:(NSString *) relationship didFinishBlock:(ActiveConnectionBlock)didFinishBlock didFailBlock:(ActiveConnectionBlock)didFailBlock{
ActiveRequest *request = [self requestForFetch];
request.delegate = nil;
if(relationship)
request.urlPath = [self relationshipURL:relationship forAction:Read];
[[[self class] activeManager] addRequest:request didParseObjectBlock:nil didFinishBlock:^(ActiveResult *result){
[self connectionDidFinish:result];
if(didFinishBlock != nil)
didFinishBlock(result);
} didFailBlock:didFailBlock];
}
- (ActiveRequest *) requestForFetch{
ActiveRequest *request = [ActiveRequest requestWithURLPath:[self resourceURLForAction:Read]];
request.httpMethod = @"GET";
request.delegate = self;
return request;
}
- (void) push{
ActiveRequest *request = [self requestForPush];
request.didFinishSelector = _remoteDidFinishSelector;
request.didFailSelector = _remoteDidFailSelector;
request.delegate = _delegate;
[[[self class] activeManager] addRequest:request];
}
- (void) push:(id) delegate didFinishSelector:(SEL) didFinishSelector didFailSelector:(SEL)didFailSelector{
ActiveRequest *request = [self requestForPush];
request.didFinishSelector = didFinishSelector;
request.didFailSelector = didFailSelector;
request.delegate = delegate;
[[[self class] activeManager] addRequest:request];
}
- (void) push:(ActiveConnectionBlock)didFinishBlock didFailBlock:(ActiveConnectionBlock)didFailBlock{
ActiveRequest *request = [self requestForPush];
[[[self class] activeManager] addRequest:request didParseObjectBlock:nil didFinishBlock:didFinishBlock didFailBlock:didFailBlock];
}
- (ActiveRequest *) requestForPush{
Action action = [self isInserted] ? Create : Update;
ActiveRequest *request = [ActiveRequest requestWithURLPath:[self resourceURLForAction:action]];
[request setDelegate:_delegate];
[request setDidFinishSelector:_remoteDidFinishSelector];
[request setDidFailSelector:_remoteDidFailSelector];
[request setHttpMethod:@"POST"];
if([self isUpdated])
[request setHttpMethod:@"PUT"];
else if([self isDeleted])
[request setHttpMethod:@"DELETE"];
if(![self isDeleted]){
NSDictionary *properties = [self properties:$D([NSNumber numberWithBool:YES], @"$serializeDates", [NSNumber numberWithBool:NO], @"$relationships")];
NSDictionary *post = [[self class] usesRootNode] ? $D(properties, [[self class] rootNodeName]) : properties;
[request setHttpBody:[[[self class] activeManager] serializeObject:post]];
}
if(![self isInserted])
[self save];
return request;
}
+ (void) pull{
ActiveRequest *request = [self requestForPull];
[[self activeManager] addRequest:request];
}
+ (void) pull:(id) delegate didParseObjectSelector:(SEL)didParseObjectSelector didFinishSelector:(SEL) didFinishSelector didFailSelector:(SEL)didFailSelector{
ActiveRequest *request = [self requestForPull];
request.didFinishSelector = didFinishSelector;
request.didFailSelector = didFailSelector;
request.didParseObjectSelector = didParseObjectSelector;
request.delegate = delegate;
[[[self class] activeManager] addRequest:request];
}
+ (void) pull:(ActiveConnectionDidParseObjectBlock)didParseObjectBlock didFinishBlock:(ActiveConnectionBlock)didFinishBlock didFailBlock:(ActiveConnectionBlock)didFailBlock{
ActiveRequest *request = [self requestForPull];
[[[self class] activeManager] addRequest:request didParseObjectBlock:didParseObjectBlock didFinishBlock:didFinishBlock didFailBlock:didFailBlock];
[self save];
}
+ (ActiveRequest *) requestForPull{
ActiveRequest *request = [ActiveRequest requestWithURLPath:[self remoteURLForAction:Read]];
[request setDelegate:[self class]];
[request setHttpMethod:@"GET"];
[request setBatch:YES];
return request;
}
- (NSString *) relationshipForURLPath:(NSString *) urlPath{
NSString *url = [urlPath stringByReplacingOccurrencesOfString:$S(@".%@", [[[self class] activeManager] remoteContentFormat]) withString:@""];
NSArray *divider = [url componentsSeparatedByString:@"?"];
NSArray *pieces = [[divider objectAtIndex:0] componentsSeparatedByString:@"/"];
[pieces makeObjectsPerformSelector:@selector(lowercaseString)];
for(NSString *relationship in [[self class] relationshipsByName]){
if([pieces containsObject:[relationship lowercaseString]])
return [relationship lowercaseString];
}
return nil;
}
- (Class) classForRelationship:(NSString *) relationship{
NSRelationshipDescription *desc = [[[self class] relationshipsByName] objectForKey:relationship];
return NSClassFromString([[desc destinationEntity] name]);
}
#pragma mark -
#pragma mark Remote Delegate
+ (void) connectionDidFinish:(ActiveResult *) result{
if([result count] > 0){
for(id object in result)
[self build:object];
[self save];
}
}
+ (void) connectionDidFail:(ActiveResult *) result{
NSLog(@"Connection Failed: %@", [result error]);
}
- (void) connectionDidFinish:(ActiveResult *) result{
NSString *relationship = [self relationshipForURLPath:result.urlPath];
NSLog(@"RELATIONSHIP = %@", relationship);
ActiveRecord *threadSafeSelf = [self threadSafe];
if(relationship)
[threadSafeSelf update:$D([result objects], relationship)];
else
[threadSafeSelf update:[result object]];
[threadSafeSelf save];
}
- (void) connectionDidFail:(ActiveResult *) result{
[[self class] connectionDidFail:result];
}