This repository has been archived by the owner on Apr 17, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 154
/
resource.rb
1222 lines (1103 loc) · 31.3 KB
/
resource.rb
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
# TODO: DRY up raise_on_save_failure with attr_accessor_with_default
# once AS branch is merged in
module DataMapper
module Resource
include DataMapper::Assertions
extend Chainable
# @deprecated
def self.append_inclusions(*inclusions)
raise "DataMapper::Resource.append_inclusions is deprecated, use DataMapper::Model.append_inclusions instead (#{caller.first})"
end
# @deprecated
def self.extra_inclusions
raise "DataMapper::Resource.extra_inclusions is deprecated, use DataMapper::Model.extra_inclusions instead (#{caller.first})"
end
# @deprecated
def self.descendants
raise "DataMapper::Resource.descendants is deprecated, use DataMapper::Model.descendants instead (#{caller.first})"
end
# Return if Resource#save should raise an exception on save failures (per-resource)
#
# This delegates to model.raise_on_save_failure by default.
#
# user.raise_on_save_failure # => false
#
# @return [Boolean]
# true if a failure in Resource#save should raise an exception
#
# @api public
def raise_on_save_failure
if defined?(@raise_on_save_failure)
@raise_on_save_failure
else
model.raise_on_save_failure
end
end
# Specify if Resource#save should raise an exception on save failures (per-resource)
#
# @param [Boolean]
# a boolean that if true will cause Resource#save to raise an exception
#
# @return [Boolean]
# true if a failure in Resource#save should raise an exception
#
# @api public
def raise_on_save_failure=(raise_on_save_failure)
@raise_on_save_failure = raise_on_save_failure
end
# Deprecated API for updating attributes and saving Resource
#
# @see #update
#
# @deprecated
def update_attributes(attributes = {}, *allowed)
raise "#{model}#update_attributes is deprecated, use #{model}#update instead (#{caller.first})"
end
# Makes sure a class gets all the methods when it includes Resource
#
# @api private
def self.included(model)
model.extend Model
end
# @api public
alias_method :model, :class
# Get the persisted state for the resource
#
# @return [Resource::State]
# the current persisted state for the resource
#
# @api private
def persisted_state
@_state ||= Resource::State::Transient.new(self)
end
# Set the persisted state for the resource
#
# @param [Resource::State]
# the new persisted state for the resource
#
# @return [undefined]
#
# @api private
def persisted_state=(state)
@_state = state
end
# Test if the persisted state is set
#
# @return [Boolean]
# true if the persisted state is set
#
# @api private
def persisted_state?
defined?(@_state) ? true : false
end
# Repository this resource belongs to in the context of this collection
# or of the resource's class.
#
# @return [Repository]
# the respository this resource belongs to, in the context of
# a collection OR in the instance's Model's context
#
# @api semipublic
def repository
# only set @_repository explicitly when persisted
defined?(@_repository) ? @_repository : model.repository
end
# Retrieve the key(s) for this resource.
#
# This always returns the persisted key value,
# even if the key is changed and not yet persisted.
# This is done so all relations still work.
#
# @return [Array(Key)]
# the key(s) identifying this resource
#
# @api public
def key
return @_key if defined?(@_key)
model_key = model.key(repository_name)
key = model_key.map do |property|
original_attributes[property] || (property.loaded?(self) ? property.get!(self) : nil)
end
# only memoize a valid key
@_key = key if model_key.valid?(key)
end
# Checks if this Resource instance is new
#
# @return [Boolean]
# true if the resource is new and not saved
#
# @api public
def new?
persisted_state.kind_of?(State::Transient)
end
# Checks if this Resource instance is saved
#
# @return [Boolean]
# true if the resource has been saved
#
# @api public
def saved?
persisted_state.kind_of?(State::Persisted)
end
# Checks if this Resource instance is destroyed
#
# @return [Boolean]
# true if the resource has been destroyed
#
# @api public
def destroyed?
readonly? && !key.nil?
end
# Checks if the resource has no changes to save
#
# @return [Boolean]
# true if the resource may not be persisted
#
# @api public
def clean?
persisted_state.kind_of?(State::Clean) || persisted_state.kind_of?(State::Immutable)
end
# Checks if the resource has unsaved changes
#
# @return [Boolean]
# true if resource may be persisted
#
# @api public
def dirty?
run_once(true) do
dirty_self? || dirty_parents? || dirty_children?
end
end
# Checks if this Resource instance is readonly
#
# @return [Boolean]
# true if the resource cannot be persisted
#
# @api public
def readonly?
persisted_state.kind_of?(State::Immutable)
end
# Returns the value of the attribute.
#
# Do not read from instance variables directly, but use this method.
# This method handles lazy loading the attribute and returning of
# defaults if nessesary.
#
# @example
# class Foo
# include DataMapper::Resource
#
# property :first_name, String
# property :last_name, String
#
# def full_name
# "#{attribute_get(:first_name)} #{attribute_get(:last_name)}"
# end
#
# # using the shorter syntax
# def name_for_address_book
# "#{last_name}, #{first_name}"
# end
# end
#
# @param [Symbol] name
# name of attribute to retrieve
#
# @return [Object]
# the value stored at that given attribute
# (nil if none, and default if necessary)
#
# @api public
def attribute_get(name)
persisted_state.get(properties[name])
end
alias_method :[], :attribute_get
# Sets the value of the attribute and marks the attribute as dirty
# if it has been changed so that it may be saved. Do not set from
# instance variables directly, but use this method. This method
# handles the lazy loading the property and returning of defaults
# if nessesary.
#
# @example
# class Foo
# include DataMapper::Resource
#
# property :first_name, String
# property :last_name, String
#
# def full_name(name)
# name = name.split(' ')
# attribute_set(:first_name, name[0])
# attribute_set(:last_name, name[1])
# end
#
# # using the shorter syntax
# def name_from_address_book(name)
# name = name.split(', ')
# first_name = name[1]
# last_name = name[0]
# end
# end
#
# @param [Symbol] name
# name of attribute to set
# @param [Object] value
# value to store
#
# @return [undefined]
#
# @api public
def attribute_set(name, value)
self.persisted_state = persisted_state.set(properties[name], value)
end
alias_method :[]=, :attribute_set
# Gets all the attributes of the Resource instance
#
# @param [Symbol] key_on
# Use this attribute of the Property as keys.
# defaults to :name. :field is useful for adapters
# :property or nil use the actual Property object.
#
# @return [Hash]
# All the attributes
#
# @api public
def attributes(key_on = :name)
attributes = {}
lazy_load(properties)
fields.each do |property|
if model.public_method_defined?(name = property.name)
key = case key_on
when :name then name
when :field then property.field
else property
end
attributes[key] = __send__(name)
end
end
attributes
end
# Assign values to multiple attributes in one call (mass assignment)
#
# @param [Hash] attributes
# names and values of attributes to assign
#
# @return [Hash]
# names and values of attributes assigned
#
# @api public
def attributes=(attributes)
model = self.model
attributes.each do |name, value|
case name
when String, Symbol
if model.public_method_defined?(setter = "#{name}=")
__send__(setter, value)
else
raise ArgumentError, "The attribute '#{name}' is not accessible in #{model}"
end
when Associations::Relationship, Property
self.persisted_state = persisted_state.set(name, value)
end
end
end
# Reloads association and all child association
#
# This is accomplished by resetting the Resource key to it's
# original value, and then removing all the ivars for properties
# and relationships. On the next access of those ivars, the
# resource will eager load what it needs. While this is more of
# a lazy reload, it should result in more consistent behavior
# since no cached results will remain from the initial load.
#
# @return [Resource]
# the receiver, the current Resource instance
#
# @api public
def reload
if key
reset_key
clear_subjects
end
self.persisted_state = persisted_state.rollback
self
end
# Updates attributes and saves this Resource instance
#
# @param [Hash] attributes
# attributes to be updated
#
# @return [Boolean]
# true if resource and storage state match
#
# @api public
def update(attributes)
assert_update_clean_only(:update)
self.attributes = attributes
save
end
# Updates attributes and saves this Resource instance, bypassing hooks
#
# @param [Hash] attributes
# attributes to be updated
#
# @return [Boolean]
# true if resource and storage state match
#
# @api public
def update!(attributes)
assert_update_clean_only(:update!)
self.attributes = attributes
save!
end
# Save the instance and loaded, dirty associations to the data-store
#
# @return [Boolean]
# true if Resource instance and all associations were saved
#
# @api public
def save
assert_not_destroyed(:save)
retval = _save
assert_save_successful(:save, retval)
retval
end
# Save the instance and loaded, dirty associations to the data-store, bypassing hooks
#
# @return [Boolean]
# true if Resource instance and all associations were saved
#
# @api public
def save!
assert_not_destroyed(:save!)
retval = _save(false)
assert_save_successful(:save!, retval)
retval
end
# Destroy the instance, remove it from the repository
#
# @return [Boolean]
# true if resource was destroyed
#
# @api public
def destroy
return true if destroyed?
catch :halt do
before_destroy_hook
_destroy
after_destroy_hook
end
destroyed?
end
# Destroy the instance, remove it from the repository, bypassing hooks
#
# @return [Boolean]
# true if resource was destroyed
#
# @api public
def destroy!
return true if destroyed?
_destroy(false)
destroyed?
end
# Compares another Resource for equality
#
# Resource is equal to +other+ if they are the same object
# (identical object_id) or if they are both of the *same model* and
# all of their attributes are equivalent
#
# @param [Resource] other
# the other Resource to compare with
#
# @return [Boolean]
# true if they are equal, false if not
#
# @api public
def eql?(other)
return true if equal?(other)
instance_of?(other.class) && cmp?(other, :eql?)
end
# Compares another Resource for equivalency
#
# Resource is equivalent to +other+ if they are the same object
# (identical object_id) or all of their attribute are equivalent
#
# @param [Resource] other
# the other Resource to compare with
#
# @return [Boolean]
# true if they are equivalent, false if not
#
# @api public
def ==(other)
return true if equal?(other)
return false unless other.kind_of?(Resource) && model.base_model.equal?(other.model.base_model)
cmp?(other, :==)
end
# Compares two Resources to allow them to be sorted
#
# @param [Resource] other
# The other Resource to compare with
#
# @return [Integer]
# Return 0 if Resources should be sorted as the same, -1 if the
# other Resource should be after self, and 1 if the other Resource
# should be before self
#
# @api public
def <=>(other)
model = self.model
unless other.kind_of?(model.base_model)
raise ArgumentError, "Cannot compare a #{other.class} instance with a #{model} instance"
end
model.default_order(repository_name).each do |direction|
cmp = direction.get(self) <=> direction.get(other)
return cmp if cmp.nonzero?
end
0
end
# Returns hash value of the object.
# Two objects with the same hash value assumed equal (using eql? method)
#
# DataMapper resources are equal when their models have the same hash
# and they have the same set of properties
#
# When used as key in a Hash or Hash subclass, objects are compared
# by eql? and thus hash value has direct effect on lookup
#
# @api private
def hash
key.hash
end
# Get a Human-readable representation of this Resource instance
#
# Foo.new #=> #<Foo name=nil updated_at=nil created_at=nil id=nil>
#
# @return [String]
# Human-readable representation of this Resource instance
#
# @api public
def inspect
# TODO: display relationship values
attrs = properties.map do |property|
value = if new? || property.loaded?(self)
property.get!(self).inspect
else
'<not loaded>'
end
"#{property.instance_variable_name}=#{value}"
end
"#<#{model.name} #{attrs.join(' ')}>"
end
# Hash of original values of attributes that have unsaved changes
#
# @return [Hash]
# original values of attributes that have unsaved changes
#
# @api semipublic
def original_attributes
if persisted_state.respond_to?(:original_attributes)
persisted_state.original_attributes.dup.freeze
else
{}.freeze
end
end
# Checks if an attribute has been loaded from the repository
#
# @example
# class Foo
# include DataMapper::Resource
#
# property :name, String
# property :description, Text, :lazy => false
# end
#
# Foo.new.attribute_loaded?(:description) #=> false
#
# @return [Boolean]
# true if ivar +name+ has been loaded
#
# @return [Boolean]
# true if ivar +name+ has been loaded
#
# @api private
def attribute_loaded?(name)
properties[name].loaded?(self)
end
# Checks if an attribute has unsaved changes
#
# @param [Symbol] name
# name of attribute to check for unsaved changes
#
# @return [Boolean]
# true if attribute has unsaved changes
#
# @api semipublic
def attribute_dirty?(name)
dirty_attributes.key?(properties[name])
end
# Hash of attributes that have unsaved changes
#
# @return [Hash]
# attributes that have unsaved changes
#
# @api semipublic
def dirty_attributes
dirty_attributes = {}
original_attributes.each_key do |property|
next unless property.respond_to?(:dump)
dirty_attributes[property] = property.dump(property.get!(self))
end
dirty_attributes
end
# Returns the Collection the Resource is associated with
#
# @return [nil]
# nil if this is a new record
# @return [Collection]
# a Collection that self belongs to
#
# @api private
def collection
return @_collection if @_collection || new? || readonly?
collection_for_self
end
# Associates a Resource to a Collection
#
# @param [Collection, nil] collection
# the collection to associate the resource with
#
# @return [nil]
# nil if this is a new record
# @return [Collection]
# a Collection that self belongs to
#
# @api private
def collection=(collection)
@_collection = collection
end
# Return a collection including the current resource only
#
# @return [Collection]
# a collection containing self
#
# @api private
def collection_for_self
Collection.new(query, [ self ])
end
# Returns a Query that will match the resource
#
# @return [Query]
# Query that will match the resource
#
# @api semipublic
def query
repository.new_query(model, :fields => fields, :conditions => conditions)
end
protected
# Method for hooking callbacks before resource saving
#
# @return [undefined]
#
# @api private
def before_save_hook
execute_hooks_for(:before, :save)
end
# Method for hooking callbacks after resource saving
#
# @return [undefined]
#
# @api private
def after_save_hook
execute_hooks_for(:after, :save)
end
# Method for hooking callbacks before resource creation
#
# @return [undefined]
#
# @api private
def before_create_hook
execute_hooks_for(:before, :create)
end
# Method for hooking callbacks after resource creation
#
# @return [undefined]
#
# @api private
def after_create_hook
execute_hooks_for(:after, :create)
end
# Method for hooking callbacks before resource updating
#
# @return [undefined]
#
# @api private
def before_update_hook
execute_hooks_for(:before, :update)
end
# Method for hooking callbacks after resource updating
#
# @return [undefined]
#
# @api private
def after_update_hook
execute_hooks_for(:after, :update)
end
# Method for hooking callbacks before resource destruction
#
# @return [undefined]
#
# @api private
def before_destroy_hook
execute_hooks_for(:before, :destroy)
end
# Method for hooking callbacks after resource destruction
#
# @return [undefined]
#
# @api private
def after_destroy_hook
execute_hooks_for(:after, :destroy)
end
private
# Initialize a new instance of this Resource using the provided values
#
# @param [Hash] attributes
# attribute values to use for the new instance
#
# @return [Hash]
# attribute values used in the new instance
#
# @api public
def initialize(attributes = nil) # :nodoc:
self.attributes = attributes if attributes
end
# @api private
def initialize_copy(original)
instance_variables.each do |ivar|
instance_variable_set(ivar, instance_variable_get(ivar).try_dup)
end
self.persisted_state = persisted_state.class.new(self)
end
# Returns name of the repository this object
# was loaded from
#
# @return [String]
# name of the repository this object was loaded from
#
# @api private
def repository_name
repository.name
end
# Gets this instance's Model's properties
#
# @return [PropertySet]
# List of this Resource's Model's properties
#
# @api private
def properties
model.properties(repository_name)
end
# Gets this instance's Model's relationships
#
# @return [RelationshipSet]
# List of this instance's Model's Relationships
#
# @api private
def relationships
model.relationships(repository_name)
end
# Returns the identity map for the model from the repository
#
# @return [IdentityMap]
# identity map of repository this object was loaded from
#
# @api private
def identity_map
repository.identity_map(model)
end
# @api private
def add_to_identity_map
identity_map[key] = self
end
# @api private
def remove_from_identity_map
identity_map.delete(key)
end
# Fetches all the names of the attributes that have been loaded,
# even if they are lazy but have been called
#
# @return [Array<Property>]
# names of attributes that have been loaded
#
# @api private
def fields
properties.select do |property|
property.loaded?(self) || (new? && property.default?)
end
end
# Reset the key to the original value
#
# @return [undefined]
#
# @api private
def reset_key
properties.key.zip(key) do |property, value|
property.set!(self, value)
end
end
# Remove all the ivars for properties and relationships
#
# @return [undefined]
#
# @api private
def clear_subjects
model_properties = properties
(model_properties - model_properties.key | relationships).each do |subject|
next unless subject.loaded?(self)
remove_instance_variable(subject.instance_variable_name)
end
end
# Lazy loads attributes not yet loaded
#
# @param [Array<Property>] properties
# the properties to reload
#
# @return [self]
#
# @api private
def lazy_load(properties)
eager_load(properties - fields)
end
# Reloads specified attributes
#
# @param [Array<Property>] properties
# the properties to reload
#
# @return [Resource]
# the receiver, the current Resource instance
#
# @api private
def eager_load(properties)
unless properties.empty? || key.nil? || collection.nil?
# set an initial value to prevent recursive lazy loads
properties.each { |property| property.set!(self, nil) }
collection.reload(:fields => properties)
end
self
end
# Return conditions to match the Resource
#
# @return [Hash]
# query conditions
#
# @api private
def conditions
key = self.key
if key
model.key_conditions(repository, key)
else
conditions = {}
properties.each do |property|
next unless property.loaded?(self)
conditions[property] = property.get!(self)
end
conditions
end
end
# @api private
def parent_relationships
parent_relationships = []
relationships.each do |relationship|
next unless relationship.respond_to?(:resource_for)
set_default_value(relationship)
next unless relationship.loaded?(self) && relationship.get!(self)
parent_relationships << relationship
end
parent_relationships
end
# Returns loaded child relationships
#
# @return [Array<Associations::OneToMany::Relationship>]
# array of child relationships for which this resource is parent and is loaded
#
# @api private
def child_relationships
child_relationships = []
relationships.each do |relationship|
next unless relationship.respond_to?(:collection_for)
set_default_value(relationship)
next unless relationship.loaded?(self)
child_relationships << relationship
end
many_to_many, other = child_relationships.partition do |relationship|
relationship.kind_of?(Associations::ManyToMany::Relationship)
end
many_to_many + other
end
# @api private
def parent_associations
parent_relationships.map { |relationship| relationship.get!(self) }
end
# @api private
def child_associations
child_relationships.map { |relationship| relationship.get_collection(self) }
end
# Commit the persisted state
#
# @return [undefined]
#
# @api private
def _persist
self.persisted_state = persisted_state.commit
end
# This method executes the hooks before and after resource creation
#
# @return [Boolean]
#
# @see Resource#_create
#
# @api private
def create_with_hooks
catch :halt do
before_save_hook
before_create_hook
_persist
after_create_hook
after_save_hook
end
end
# This method executes the hooks before and after resource updating
#
# @return [Boolean]
#
# @see Resource#_update
#
# @api private
def update_with_hooks
catch :halt do
before_save_hook
before_update_hook
_persist
after_update_hook
after_save_hook
end
end
# Destroy the resource
#
# @return [undefined]
#
# @api private
def _destroy(execute_hooks = true)
self.persisted_state = persisted_state.delete
_persist
end
# @api private
def _save(execute_hooks = true)
run_once(true) do
save_parents(execute_hooks) && save_self(execute_hooks) && save_children(execute_hooks)