This repository has been archived by the owner on Jun 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMCResource.j
1415 lines (1157 loc) · 43.6 KB
/
MCResource.j
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
@import "Constants.j"
@import "MCError.j"
@import "MCJSONDataTransformer.j"
@import "MCURLConnection.j"
@import "MCHTTPRequest.j"
@import "MCQueuedRequest.j"
@import "MCQueue.j"
@import "MCAssociation.j"
@import "MCHasOneAssociation.j"
@import "MCHasManyAssociation.j"
@import "MCBelongsToAssociation.j"
@import "CPString-MCResourceAdditions.j"
@import "CPDate-MCResourceAdditions.j"
@import "CPArrayController-MCResourceAdditions.j"
@import "CPArray-MCResourceAdditions.j"
@import "MCValidation.j"
MCResourceServerURLPrefix = @"";
// Options dictionary key names
MCResourceAssociationClassKey = @"MCResourceAssociationClassKey";
MCResourceAssociationObjectClassKey = @"MCResourceAssociationObjectClassKey";
MCResourceAssociationAutosaveKey = @"MCResourceAssociationAutosaveKey";
MCResourceAssociationShallowKey = @"MCResourceAssociationShallowKey";
MCResourceAssociationNestedOnlyKey = @"MCResourceAssociationNestedOnlyKey";
MCResourceAssociationSortDescriptorsKey = @"MCResourceAssociationSortDescriptorsKey";
MCResourceAssociationCustomURLKey = @"MCResourceAssociationCustomURLKey";
// These are all file-scoped
var classAttributesDictionary = [CPDictionary dictionary];
var classMethodDelegateDictionary = [CPDictionary dictionary];
var classMethodSelectorDictionary = [CPDictionary dictionary];
var classAssociationsDictionary = [CPDictionary dictionary];
var classValidationsDictionary = [CPDictionary dictionary];
var classUniqueAttributesDictionary = [CPDictionary dictionary];
var _MCResourceErrorAlertIsShowing = NO;
var AllResourcesByTypeAndId = [CPDictionary dictionary];
/*
* MCResource
*
* This is where the magic happens. Syntax and methods are strongly inspired by ActiveRecord, part of Ruby on Rails, (c) 37signals
* The most notable difference is, this class does not support synchronous requesting, so EVERY request must be made with separate
* requesting and processing parts. It will usually work with a delegate callback.
*
*/
@implementation MCResource : CPObject
{
// Common attributes that every record has
CPDate createdAt;
CPDate updatedAt;
// Internal attributes - all of these MUST begin with an underscore to avoid conflicts with model attribute names!
CPDictionary _changes;
CPDictionary _changesForRemote;
CPString _identifier;
CPDictionary _associations;
CPDictionary _errors;
MCAssociation _reflection;
CPDictionary _instanceMethodDelegateDictionary;
CPDictionary _instanceMethodSelectorDictionary;
CPURL _resourceURL;
BOOL _isReloading;
}
#pragma mark -
#pragma mark Setup methods (Behavior)
// Override this to make this resource behave like a singleton
+ (BOOL)isSingletonResource
{
return NO;
}
// Override this to set a custom identifier field. Default is "id"
+ (CPString)identifierKey
{
return "id";
}
// Override this to set a custom wrapping name for saving / loading
+ (CPString)railsName
{
return [[self className] railsifiedString];
}
// Mark unique attributes with this method
// This will affect saving behavior
+ (void)hasUniqueAttribute:(CPString)attributeName
{
var uniqueAttributes = [classUniqueAttributesDictionary objectForKey:[self className]];
if(!uniqueAttributes)
{
[classUniqueAttributesDictionary setObject:[attributeName] forKey:[self className]];
}
else
{
[uniqueAttributes addObject:attributeName];
}
}
+ (CPArray)uniqueAttributes
{
return [classUniqueAttributesDictionary objectForKey:[self className]];
}
#pragma mark -
#pragma mark Setup methods (Associations)
+ (void)hasOne:(CPString)aName
{
[self addAssociationWithName:aName class:MCHasOneAssociation options:[CPDictionary dictionary]];
}
+ (void)hasOne:(CPString)aName options:(CPDictionary)options
{
[self addAssociationWithName:aName class:MCHasOneAssociation options:options];
}
+ (void)hasMany:(CPString)aName
{
[self addAssociationWithName:aName class:MCHasManyAssociation options:[CPDictionary dictionary]];
}
+ (void)hasMany:(CPString)aName options:(CPDictionary)options
{
[self addAssociationWithName:aName class:MCHasManyAssociation options:options];
}
+ (void)belongsTo:(CPString)aName
{
[self addAssociationWithName:aName class:MCBelongsToAssociation options:[CPDictionary dictionary]];
}
+ (void)belongsTo:(CPString)aName options:(CPDictionary)options
{
[self addAssociationWithName:aName class:MCBelongsToAssociation options:options];
}
+ (void)addAssociationWithName:(CPString)aName class:(Class)associationClass options:(CPDictionary)options
{
var associatedObjectClass, autosave, shallow, isNestedOnly, sortDescriptors;
if(!options || !(associatedObjectClass = [options objectForKey:MCResourceAssociationObjectClassKey]))
{
if(associationClass === MCHasManyAssociation)
associatedObjectClass = objj_getClass([[aName singularize] cappifiedClass]);
else
associatedObjectClass = objj_getClass([aName cappifiedClass]);
}
if(!options || !(sortDescriptors = [options objectForKey:MCResourceAssociationSortDescriptorsKey]))
{
sortDescriptors = [];
}
if(!associatedObjectClass)
{
CPLog.error(@"Could not find class '" + [aName cappifiedClass] + "' for association in object " + [self className]);
}
if(!options || !(autosave = [options objectForKey:MCResourceAssociationAutosaveKey]))
{
autosave = NO;
}
if(!options || !(shallow = [options objectForKey:MCResourceAssociationShallowKey]))
{
shallow = NO;
}
if(!options || !(isNestedOnly = [options objectForKey:MCResourceAssociationNestedOnlyKey]))
{
isNestedOnly = NO;
}
customURL = [options objectForKey:MCResourceAssociationCustomURLKey];
// Add the association to the class ivars
// Just as if you had typed "MCHas(One|Many)Association <name>" in the class declaration
class_addIvar(self, aName, [associationClass className]);
// Remember this association's options
if(![classAssociationsDictionary objectForKey:[self className]])
{
[classAssociationsDictionary setObject:[CPDictionary dictionary] forKey:[self className]];
}
var optionsDictionary = [CPDictionary dictionaryWithObjects:[associationClass,
associatedObjectClass,
autosave,
shallow,
isNestedOnly,
sortDescriptors,
customURL]
forKeys:[MCResourceAssociationClassKey,
MCResourceAssociationObjectClassKey,
MCResourceAssociationAutosaveKey,
MCResourceAssociationShallowKey,
MCResourceAssociationNestedOnlyKey,
MCResourceAssociationSortDescriptorsKey,
MCResourceAssociationCustomURLKey]];
[[classAssociationsDictionary objectForKey:[self className]] setObject:optionsDictionary forKey:aName];
}
#pragma mark -
#pragma mark Overrides
- (id)copy
{
var copy = [[[self class] alloc] init];
[copy setAttributes:[self attributes]];
// Strip identifier from the copy
[copy _setValue:nil forKey:@"identifier"];
return copy;
}
- (id)clone
{
// FIXME: Copy attributes by copying ivars one by one
var aClass = [self class];
var clone = [[aClass alloc] init];
var attributeNames = [[[clone class] attributes] allKeys];
while([aClass superclass])
{
// clone ivars
var ivarList = class_copyIvarList(aClass);
var ivarCount = [ivarList count];
while(ivarCount--)
{
var ivarName = [ivarList objectAtIndex:ivarCount].name;
clone[ivarName] = self[ivarName];
}
aClass = [aClass superclass];
}
// Set attribute changes
var attributes = [[[self class] attributes] allKeys],
attributeCount = [attributes count];
while(attributeCount--)
{
[[clone changes] setValue:@"" forKey:[attributes objectAtIndex:attributeCount]];
}
[clone commit];
return clone;
}
// Default & designated initializer
- (id)init
{
if(self = [super init])
{
// Initialize instance variables
_instanceMethodSelectorDictionary = [CPDictionary dictionary];
_instanceMethodDelegateDictionary = [CPDictionary dictionary];
_identifier = "";
_changes = [CPDictionary dictionary];
_changesForRemote = [CPDictionary dictionary];
_associations = [CPDictionary dictionary];
_errors = [CPDictionary dictionary];
// Setup associations
var associationNames = [[classAssociationsDictionary objectForKey:[self className]] allKeys];
for(var i = 0; i < [associationNames count]; i++)
{
var associationName = [associationNames objectAtIndex:i];
var associationOptions = [[classAssociationsDictionary objectForKey:[self className]] objectForKey:associationName];
var associationTypeClass = [associationOptions objectForKey:MCResourceAssociationClassKey];
var associationClass = [associationOptions objectForKey:MCResourceAssociationObjectClassKey];
var association = [[associationTypeClass alloc] initWithName:associationName class:associationClass parent:self];
var autosaves = [associationOptions objectForKey:MCResourceAssociationAutosaveKey];
var shallow = [associationOptions objectForKey:MCResourceAssociationShallowKey];
var nestedOnly = [associationOptions objectForKey:MCResourceAssociationNestedOnlyKey];
var sortDescriptors = [associationOptions objectForKey:MCResourceAssociationSortDescriptorsKey];
var customURL = [associationOptions objectForKey:MCResourceAssociationCustomURLKey];
[association setAutosaves:autosaves];
[association setIsShallow:shallow];
[association setNestedOnly:nestedOnly];
if(customURL)
{
[association setCustomURL:customURL];
}
if(associationTypeClass == MCHasManyAssociation && [sortDescriptors count] > 0)
{
[association setSortDescriptors:sortDescriptors];
}
[_associations setObject:association forKey:associationName];
[self _setValue:association forKey:associationName];
// Add a method to get the association
class_addMethod(self.isa, sel_getUid(associationName), function(self, _cmd)
{
return self[_cmd];
},["id"]);
// FIXME: Add a proxy method to set the association
// class_addMethod(self.isa, sel_getUid("set" + associationName + ":"), function(self, _cmd, anObject)
// {
// if([association isKindOfClass:[MCHasManyAssociation class]])
// {
// console.log("NOT SUPPORTED YET set(HasManyAssociation):");
// }
// else
// {
// [association setAssociatedObject:anObject];
// }
// },["", "id"]);
}
}
return self;
}
// This is a standard override for development purposes - if log output gets too messy, remove it.
- (CPString)description
{
var description = [self className] + ", ID " + [self identifier] + ": { \n",
attributes = [[[self class] attributes] keyEnumerator],
attribute;
while(attribute = [attributes nextObject])
{
if([_associations containsKey:attribute])
attributeDescription = [self associationForName:attribute];
else
attributeDescription = [self valueForKey:attribute];
description += [CPString stringWithFormat:@"\t %@ = '%@'\n", attribute, attributeDescription];
}
description += "};";
return description;
}
#pragma mark -
#pragma mark Public methods
- (MCAssociation)associationForName:(CPString)aName
{
return [_associations objectForKey:aName];
}
+ (MCResource)getResourceWithId:(int)anIdentifier ofClass:(Class)resourceClass
{
return [AllResourcesByTypeAndId valueForKeyPath:resourceClass + "." + anIdentifier];
}
+ (CPArray)allResourcesOfClass:(Class)resourceClass
{
return [AllResourcesByTypeAndId valueForKey:resourceClass]
}
// Find associated records under the URL of the parent record
+ (void)findAsAssociated:(CPDictionary)params withDelegate:(id)aDelegate andSelector:(SEL)aSelector parent:(MCResource)parent
{
resourceURL = [parent resourceURL] + '/' + [self _constructResourceURL];
[self find:params withDelegate:aDelegate andSelector:aSelector resourceURL:resourceURL];
}
// Find a record on the server with the given params
+ (void)find:(CPDictionary)params withDelegate:(id)aDelegate andSelector:(SEL)aSelector
{
[self find:params withDelegate:aDelegate andSelector:aSelector resourceURL:[self resourceURL]];
}
+ (void)find:(CPDictionary)params withDelegate:(id)aDelegate andSelector:(SEL)aSelector resourceURL:(CPURL)resourceURL
{
// Add the passed-in parameters to our request
if(params)
{
resourceURL += [CPString parameterStringFromDictionary:params];
}
// Construct a request
var target = [CPURL URLWithString:resourceURL],
request = [MCHTTPRequest requestTarget:target withMethod:@"GET" andDelegate:self],
queuedRequest = [MCQueuedRequest queuedRequestWithRequest:request];
// Register the callback in our file-scoped callback dictionary
[classMethodDelegateDictionary setObject:aDelegate forKey:queuedRequest];
[classMethodSelectorDictionary setObject:aSelector forKey:queuedRequest];
// Append the wrapped request to the queue
[[MCQueue sharedQueue] appendRequest:queuedRequest];
}
// Save a resource on the server. Automatically saves associations along with the resource.
- (MCQueuedRequest)saveWithDelegate:(id)aDelegate andSelector:(SEL)aSelector
{
return [self saveWithDelegate:aDelegate andSelector:aSelector startImmediately:YES];
}
- (MCQueuedRequest)saveWithDelegate:(id)aDelegate andSelector:(SEL)aSelector startImmediately:(BOOL)startImmediately
{
// Commit uncommitted changed
[self commit];
// Build a save request
var masterRequest = [self _buildSaveRequest];
// If there's nothing to save, consider it a success and call the delegate's selector
if(!masterRequest)
{
if(aDelegate && aSelector && startImmediately)
[aDelegate performSelector:aSelector withObject:self];
return nil;
}
// Register the callback in our instance's callback dictionary
[_instanceMethodDelegateDictionary setObject:aDelegate forKey:masterRequest];
[_instanceMethodSelectorDictionary setObject:aSelector forKey:masterRequest];
// Append the wrapped request to the queue if appropriate
if(startImmediately)
[[MCQueue sharedQueue] appendRequest:masterRequest];
return masterRequest;
}
// Reload a resource's data via RESTful 'show' action
- (void)reloadWithDelegate:(id)aDelegate andSelector:(SEL)aSelector
{
// Construct the reload request
var request = [self _buildReloadRequest];
// Register a didReload: callback
[_instanceMethodDelegateDictionary setObject:aDelegate forKey:request];
[_instanceMethodSelectorDictionary setObject:aSelector forKey:request];
_isReloading = YES;
// Append the wrapped request to the queue
[[MCQueue sharedQueue] appendRequest:request];
}
// Delete a resource via RESTful 'delete' action
- (MCQueuedRequest)deleteWithDelegate:(id)aDelegate andSelector:(SEL)aSelector
{
return [self deleteWithDelegate:aDelegate andSelector:aSelector startImmediately:YES];
}
- (MCQueuedRequest)deleteWithDelegate:(id)aDelegate andSelector:(SEL)aSelector startImmediately:(BOOL)startImmediately
{
// Construct the delete request
var target = [CPURL URLWithString:[self resourceURL]],
request = [MCHTTPRequest requestTarget:target withMethod:@"DELETE" andDelegate:self],
queuedRequest = [MCQueuedRequest queuedRequestWithRequest:request];
// Register a didReload: callback
[_instanceMethodDelegateDictionary setObject:aDelegate forKey:queuedRequest];
[_instanceMethodSelectorDictionary setObject:aSelector forKey:queuedRequest];
// Append the wrapped request to the queue if appropriate
if(startImmediately)
[[MCQueue sharedQueue] appendRequest:queuedRequest];
return queuedRequest;
}
- (BOOL)isNewRecord
{
return !_identifier;
}
- (CPString)identifier
{
return _identifier;
}
- (void)setIdentifier:(int)identifier
{
if(_identifier && identifier != _identifier)
{
CPLog.warn(@"Re-set identifier on %@", self);
return;
}
if(isNaN(identifier))
{
[CPException raise:CPInvalidArgumentException reason:@"Identifier must be a number but was " + identifier + " (" + typeof identifier + ")" + " (Object: " + self + ")"];
return;
}
_identifier = identifier;
// Take care of registering the product in our global AllResourcesByTypeAndId dictionary
var resourcesByType = [AllResourcesByTypeAndId objectForKey:[self className]];
if(!resourcesByType)
{
[AllResourcesByTypeAndId setObject:[CPDictionary dictionaryWithObject:self forKey:_identifier] forKey:[self className]];
}
else
{
[resourcesByType setObject:self forKey:_identifier];
}
}
// Returns a dictionary containing all the resource's attributes
- (CPDictionary)attributes
{
var returnedDictionary = [CPDictionary dictionary],
associations = [[classAssociationsDictionary objectForKey:[self className]] allKeys],
attributeNames = [[[self class] attributes] allKeys],
attributeEnumerator = [attributeNames objectEnumerator],
attribute;
// Run through all attributes
while(attribute = [attributeEnumerator nextObject])
{
// Obviously, we don't want to include associations here
if([associations containsObject:attribute])
{
continue;
}
[returnedDictionary setObject:[self valueForKey:attribute] forKey:[attribute railsifiedString]];
}
// Wrap the attributes under another root dictionary with the class name
var wrappedDictionary = [CPDictionary dictionaryWithObject:returnedDictionary forKey:[[self className] railsifiedString]];
return wrappedDictionary;
}
#pragma mark -
#pragma mark Change management
// Returns the raw change dictionary
- (CPDictionary)changesForRemote
{
return _changesForRemote;
}
- (BOOL)hasChangesForServer
{
return ([_changesForRemote count] > 0);
}
- (void)commit
{
[_changesForRemote addEntriesFromDictionary:_changes];
[_changes removeAllObjects];
}
- (CPDictionary)changes
{
return _changes;
}
- (BOOL)hasChanges
{
return ([_changes count] > 0);
}
// Reverts all recorded changes
- (void)revert
{
var changedKeys = [_changes keyEnumerator],
changedKey;
while(changedKey = [changedKeys nextObject])
{
[self _setValue:[_changes objectForKey:changedKey] forKey:changedKey];
}
[_changes removeAllObjects];
}
// Returns a dictionary containing only changed attributes
- (CPDictionary)attributesForSave
{
var returnedDictionary = [CPDictionary dictionary],
changedKeys = [_changesForRemote keyEnumerator],
changedKey;
while(changedKey = [changedKeys nextObject])
{
var changedValue = [self valueForKey:changedKey];
// Set empty values correctly
if((!changedValue && !(changedValue === NO) && !(changedValue === 0)) || changedValue === "")
{
changedValue = [CPNull null];
}
if(changedValue.isa && ![changedValue isKindOfClass:[MCResource class]])
{
// Set compound values correctly (convert them to dictionaries)
if([changedValue respondsToSelector:@selector(attributes)])
{
changedValue = [changedValue attributes];
}
}
[returnedDictionary setObject:changedValue forKey:[changedKey railsifiedString]];
}
// Don't return a dictionary if there's nothing to save
if([[returnedDictionary allKeys] count] === 0)
{
return nil;
}
// Wrap the attributes under another root dictionary with the class name
var wrappedDictionary = [CPDictionary dictionaryWithObject:returnedDictionary forKey:[[self class] railsName]];
return wrappedDictionary;
}
// Uses a dictionary to set the resource's attributes
- (void)setAttributes:(JSObject)attributeDictionary
{
var givenAttributes = [attributeDictionary objectForKey:[[self class] railsName]],
classAttributes = [[self class] attributes];
var identifierKey = [[self class] identifierKey],
identifier = [givenAttributes objectForKey:identifierKey];
// Special treatment for the resource identifier key
if(identifier && ![identifier isKindOfClass:[CPNull class]])
{
[self setIdentifier:identifier];
[givenAttributes removeObjectForKey:identifierKey];
}
else
{
// CPLog.warn(@"Resource " + self + " loaded without identifier key! This will likely cause problems in the future.");
}
// And normal treatment for the other keys
var attributeEnumerator = [givenAttributes keyEnumerator],
attribute;
while(attribute = [attributeEnumerator nextObject])
{
var attributeName = [attribute cappifiedString],
attributeType = [classAttributes objectForKey:attributeName];
var aValue = [givenAttributes valueForKey:attribute];
if(attributeType)
{
switch(attributeType)
{
case "CPArray":
[self _setValue:aValue forKey:attributeName];
break;
case "CPString":
// Set null values as null values, not string representations of CPNull
if(!([aValue isKindOfClass:[CPNull class]] || (typeof aValue == 'String' && aValue.length == 0)))
{
[self _setValue:aValue forKey:attributeName];
}
break;
case "CPDate":
if([aValue isKindOfClass:[CPDate class]])
{
[self _setValue:aValue forKey:attributeName];
}
else
{
[self _setValue:[CPDate dateWithDateTimeString:aValue] forKey:attributeName];
}
break;
case "CPNumber":
var parsedValue = parseFloat(aValue);
if(!isNaN(parsedValue))
{
[self _setValue:parsedValue forKey:attributeName];
}
break;
case "BOOL":
[self _setValue:!!aValue forKey:attributeName];
break;
default:
var childClassAssociation = [[classAssociationsDictionary objectForKey:[self className]] objectForKey:attributeName];
if(childClassAssociation)
{
var childClass = [childClassAssociation objectForKey:MCResourceAssociationObjectClassKey],
childClassAssociationType = [childClassAssociation objectForKey:MCResourceAssociationClassKey];
if(childClassAssociationType == MCHasManyAssociation)
{
// Parse the array
var theHasManyAssociation = [_associations objectForKey:attributeName],
childObjectDataEnumerator = [aValue objectEnumerator],
childObjectData,
initializedChildObjects = [];
while(childObjectData = [childObjectDataEnumerator nextObject])
{
var childObj = [childClass new];
[childObj setAttributes:childObjectData];
[childObj resourceDidLoad];
[initializedChildObjects addObject:childObj];
}
[theHasManyAssociation didLoadAssociatedObjects:initializedChildObjects];
}
else
{
var childObj = [childClass new];
[childObj setAttributes:[CPDictionary dictionaryWithObject:aValue forKey:[[childClass className] railsifiedString]]];
// Send out KVO-notifications for association object changes
[self willChangeValueForKey:attributeName];
[[_associations objectForKey:attributeName] setAssociatedObject:childObj];
[self didChangeValueForKey:attributeName];
[childObj resourceDidLoad];
}
}
else if((childClass = objj_getClass(attributeType)) || (childClass = objj_getClass([attributeName cappifiedClass])))
{
var childObj = [childClass new];
if([aValue isKindOfClass:[CPDictionary class]])
{
var childAttributeEnumerator = [aValue keyEnumerator],
childAttributeName;
// FIXME: Refactor in the future to get ivar class-based parsing for child objects
while(childAttributeName = [childAttributeEnumerator nextObject])
{
var value = [aValue objectForKey:childAttributeName],
parsedValue = parseFloat(value);
if(!isNaN(parsedValue))
{
value = [CPNumber numberWithFloat:parsedValue];
}
[childObj setValue:value forKey:[childAttributeName cappifiedString]];
}
// Use the KVO-notifying version of setValue:forKey: here to
// enable binding to child objects even if they are not
// associations.
[self willChangeValueForKey:attributeName];
[self _setValue:childObj forKey:attributeName];
[self didChangeValueForKey:attributeName];
}
else if(aValue === nil || [aValue isKindOfClass:[CPNull class]])
{
// Do nothing
}
else
{
CPLog.warn(@"Don't know how to parse objects of class " + [attributeName cappifiedClass] + ". Only dictionary parsing into custom objects is supported.");
}
}
else
{
CPLog.warn(@"Unknown type for attribute " + [attributeName cappifiedClass] + " in class " + [self class] + " (could not find class named " + [attributeName cappifiedClass] + " or " + attributeType + ")");
}
break;
}
}
else
{
// CPLog.warn("Could not parse attribute: " + attributeName + " into class " + [self class]);
}
}
}
- (BOOL)isReloading
{
return _isReloading;
}
#pragma mark -
#pragma mark Hooks
// Override in child classes. Will be executed right after resource was fetched from server with its attributes already set.
- (void)resourceDidLoad
{
}
#pragma mark -
#pragma mark Resource validation
+ (void)validate:(CPString)field with:(MCValidation)aValidation
{
var classValidations = [classValidationsDictionary objectForKey:[self className]];
if(!classValidations)
{
[classValidationsDictionary setObject:[CPDictionary dictionary] forKey:[self className]];
}
var fieldValidations = [classValidations objectForKey:field];
if(!fieldValidations)
{
[[classValidationsDictionary objectForKey:[self className]] setObject:[aValidation] forKey:field];
}
else
{
[fieldValidations addObject:aValidation];
}
}
- (BOOL)valid
{
var classValidations = [classValidationsDictionary objectForKey:[self className]];
var _hasError = NO;
if(!classValidations)
return YES;
[_errors removeAllObjects];
var validatedFieldEnumerator = [classValidations keyEnumerator],
validatedField;
while(validatedField = [validatedFieldEnumerator nextObject])
{
var validations = [classValidations objectForKey:validatedField],
validationEnumerator = [validations objectEnumerator],
validation;
while(validation = [validationEnumerator nextObject])
{
// console.log("Checking: " + validatedField + " value: " + [[self valueForKeyPath:validatedField] description]);
var error = [validation errorForValue:[self valueForKeyPath:validatedField]];
if(error)
{
_hasError = YES;
if(![_errors objectForKey:validatedField])
{
[_errors setObject:[CPArray array] forKey:validatedField];
}
[[_errors objectForKey:validatedField] addObject:error];
}
}
}
if(!_hasError)
{
[_errors removeAllObjects];
}
// console.log("Checked " + [self objjDescription] + " - errors: " + [_errors description]);
return !_hasError;
}
- (CPDictionary)errors
{
return _errors;
}
- (BOOL)hasErrors
{
return (_errors && [_errors count] > 0);
}
- (CPString)humanReadableErrors
{
// Generate a simple list
var errors = [self errors];
if(!errors || [errors count] == 0)
{
return @"";
}
var errorKeyEnumerator = [errors keyEnumerator],
errorKey,
errorString = @"";
while(errorKey = [errorKeyEnumerator nextObject])
{
errorString += [CPString stringWithFormat:@"• %@ %@\n", errorKey, [errors objectForKey:errorKey]];
}
return errorString;
}
#pragma mark -
#pragma mark Internal methods
- (CPString)objjDescription
{
return [self description];
}
- (MCQueuedRequest)_buildReloadRequest
{
// Construct master reload request
var target = [CPURL URLWithString:[self resourceURL]],
request = [MCHTTPRequest requestTarget:target withMethod:@"GET" andDelegate:self],
queuedRequest = [MCQueuedRequest queuedRequestWithRequest:request];
// Construct association reload requests
var associationNames = [_associations keyEnumerator],
associationName;
while(associationName = [associationNames nextObject])
{
var association = [_associations objectForKey:associationName],
associationOptions = [[classAssociationsDictionary objectForKey:[self className]] objectForKey:associationName];
// Skip associations that cannot be loaded seperately
if([associationOptions valueForKey:MCResourceAssociationNestedOnlyKey] === YES)
{
continue;
}
var subRequest = [association _buildLoadRequest];
if(subRequest)
[queuedRequest addChildRequest:subRequest];
}
return queuedRequest;
}
// Constructs a queable request intended to push the resource class to the server
- (MCQueuedRequest)_buildSaveRequest
{
return [self _buildSaveRequestWithURL:[self resourceURL]];
}
- (MCQueuedRequest)_buildSaveRequestWithURL:(CPURL)saveURL
{
// Construct a request
var target = [CPURL URLWithString:saveURL],
request = [MCHTTPRequest requestTarget:target withMethod:[self _methodForSaving] andDelegate:self];
// Pass in the model's data for saving
var savedAttributes = [self attributesForSave];
// Don't need to save when nothing has changed and the record previously existed
if([self identifier] && !savedAttributes)
return nil;
[request setData:savedAttributes];
var queuedRequest = [MCQueuedRequest queuedRequestWithRequest:request];
// Append association save requests
var associationEnumerator = [_associations objectEnumerator],
association;
while(association = [associationEnumerator nextObject])
{
if([association autosaves])
{
if([association isKindOfClass:[MCHasOneAssociation class]])
{
var associationSaveRequest = [association _buildSaveRequest];
[queuedRequest addChildRequest:associationSaveRequest];
}
else
{
var associationSaveRequests = [association _buildSaveRequests];
[queuedRequest addChildRequests:associationSaveRequests];
}
}
}
// Return a queuedRequest with sub-requests for associations
return queuedRequest;
}
// Determines HTTP method for saving - new resources should be sent with POST, existing resources with PUT
- (CPString)_methodForSaving
{