This repository has been archived by the owner on Apr 17, 2018. It is now read-only.
/
relationship.rb
386 lines (324 loc) · 13.4 KB
/
relationship.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
# TODO: update Model#respond_to? to return true if method_method missing
# would handle the message
module DataMapper
module Model
module Relationship
Model.append_extensions self
include DataMapper::Assertions
extend Chainable
# Initializes relationships hash for extended model
# class.
#
# When model calls has n, has 1 or belongs_to, relationships
# are stored in that hash: keys are repository names and
# values are relationship sets.
#
# @api private
def self.extended(model)
model.instance_variable_set(:@relationships, {})
end
chainable do
# When DataMapper model is inherited, relationships
# of parent are duplicated and copied to subclass model
#
# @api private
def inherited(model)
model.instance_variable_set(:@relationships, {})
@relationships.each do |repository_name, relationships|
model_relationships = model.relationships(repository_name)
relationships.each { |name, relationship| model_relationships[name] ||= relationship }
end
super
end
end
# Returns copy of relationships set in given repository.
#
# @param [Symbol] repository_name
# Name of the repository for which relationships set is returned
# @return [Mash] relationships set for given repository
#
# @api semipublic
def relationships(repository_name = default_repository_name)
# TODO: create RelationshipSet#copy that will copy the relationships, but assign the
# new Relationship objects to a supplied repository and model. dup does not really
# do what is needed
default_repository_name = self.default_repository_name
@relationships[repository_name] ||= if repository_name == default_repository_name
Mash.new
else
relationships(default_repository_name).dup
end
end
# Used to express unlimited cardinality of association,
# see +has+
#
# @api public
def n
Infinity
end
# A shorthand, clear syntax for defining one-to-one, one-to-many and
# many-to-many resource relationships.
#
# * has 1, :friend # one friend
# * has n, :friends # many friends
# * has 1..3, :friends # many friends (at least 1, at most 3)
# * has 3, :friends # many friends (exactly 3)
# * has 1, :friend, 'User' # one friend with the class User
# * has 3, :friends, :through => :friendships # many friends through the friendships relationship
#
# @param cardinality [Integer, Range, Infinity]
# cardinality that defines the association type and constraints
# @param name [Symbol]
# the name that the association will be referenced by
# @param model [Model, #to_str]
# the target model of the relationship
# @param opts [Hash]
# an options hash
#
# @option :through[Symbol] A association that this join should go through to form
# a many-to-many association
# @option :model[Model, String] The name of the class to associate with, if omitted
# then the association name is assumed to match the class name
# @option :repository[Symbol]
# name of child model repository
#
# @return [Association::Relationship] the relationship that was
# created to reflect either a one-to-one, one-to-many or many-to-many
# relationship
# @raise [ArgumentError] if the cardinality was not understood. Should be a
# Integer, Range or Infinity(n)
#
# @api public
def has(cardinality, name, *args)
name = name.to_sym
model = extract_model(args)
options = extract_options(args)
min, max = extract_min_max(cardinality)
options.update(:min => min, :max => max)
assert_valid_options(options)
if options.key?(:model) && model
raise ArgumentError, 'should not specify options[:model] if passing the model in the third argument'
end
model ||= options.delete(:model)
repository_name = repository.name
# TODO: change to :target_respository_name and :source_repository_name
options[:child_repository_name] = options.delete(:repository)
options[:parent_repository_name] = repository_name
klass = if max > 1
options.key?(:through) ? Associations::ManyToMany::Relationship : Associations::OneToMany::Relationship
else
Associations::OneToOne::Relationship
end
relationship = relationships(repository_name)[name] = klass.new(name, model, self, options)
descendants.each do |descendant|
descendant.relationships(repository_name)[name] ||= relationship
end
create_relationship_reader(relationship)
create_relationship_writer(relationship)
relationship
end
# A shorthand, clear syntax for defining many-to-one resource relationships.
#
# * belongs_to :user # many to one user
# * belongs_to :friend, :model => 'User' # many to one friend
# * belongs_to :reference, :repository => :pubmed # association for repository other than default
#
# @param name [Symbol]
# the name that the association will be referenced by
# @param model [Model, #to_str]
# the target model of the relationship
# @param opts [Hash]
# an options hash
#
# @option :model[Model, String] The name of the class to associate with, if omitted
# then the association name is assumed to match the class name
# @option :repository[Symbol]
# name of child model repository
#
# @return [Association::Relationship] The association created
# should not be accessed directly
#
# @api public
def belongs_to(name, *args)
name = name.to_sym
model_name = self.name
model = extract_model(args)
options = extract_options(args)
if options.key?(:through)
warn "#{model_name}#belongs_to with :through is deprecated, use 'has 1, :#{name}, #{options.inspect}' in #{model_name} instead (#{caller[0]})"
return has(1, name, model, options)
end
assert_valid_options(options)
if options.key?(:model) && model
raise ArgumentError, 'should not specify options[:model] if passing the model in the third argument'
end
model ||= options.delete(:model)
repository_name = repository.name
# TODO: change to source_repository_name and target_respository_name
options[:child_repository_name] = repository_name
options[:parent_repository_name] = options.delete(:repository)
relationship = relationships(repository_name)[name] = Associations::ManyToOne::Relationship.new(name, self, model, options)
descendants.each do |descendant|
descendant.relationships(repository_name)[name] ||= relationship
end
create_relationship_reader(relationship)
create_relationship_writer(relationship)
relationship
end
private
# Extract the model from an Array of arguments
#
# @param [Array(Model, String, Hash)]
# The arguments passed to an relationship declaration
#
# @return [Model, #to_str]
# target model for the association
#
# @api private
def extract_model(args)
model = args.first
if model.kind_of?(Model)
model
elsif model.respond_to?(:to_str)
model.to_str
else
nil
end
end
# Extract the model from an Array of arguments
#
# @param [Array(Model, String, Hash)]
# The arguments passed to an relationship declaration
#
# @return [Hash]
# options for the association
#
# @api private
def extract_options(args)
options = args.last
options.respond_to?(:to_hash) ? options.to_hash.dup : {}
end
# A support method for converting Integer, Range or Infinity values into two
# values representing the minimum and maximum cardinality of the association
#
# @return [Array] A pair of integers, min and max
#
# @api private
def extract_min_max(cardinality)
case cardinality
when Integer then [ cardinality, cardinality ]
when Range then [ cardinality.first, cardinality.last ]
when Infinity then [ 0, Infinity ]
else
assert_kind_of 'options', options, Integer, Range, Infinity.class
end
end
# Validates options of association method like belongs_to or has:
# verifies types of cardinality bounds, repository, association class,
# keys and possible values of :through option.
#
# @api private
def assert_valid_options(options)
# TODO: update to match Query#assert_valid_options
# - perform options normalization elsewhere
caller_method = caller[1]
if options.key?(:min) && options.key?(:max)
min = options[:min]
max = options[:max]
min = min.to_int unless min == Infinity
max = max.to_int unless max == Infinity
if min == Infinity && max == Infinity
raise ArgumentError, 'Cardinality may not be n..n. The cardinality specifies the min/max number of results from the association'
elsif min > max
raise ArgumentError, "Cardinality min (#{min}) cannot be larger than the max (#{max})"
elsif min < 0
raise ArgumentError, "Cardinality min much be greater than or equal to 0, but was #{min}"
elsif max < 1
raise ArgumentError, "Cardinality max much be greater than or equal to 1, but was #{max}"
end
end
if options.key?(:repository)
options[:repository] = options[:repository].to_sym
end
if options.key?(:class_name)
options[:class_name] = options[:class_name].to_str
warn "+options[:class_name]+ is deprecated, use :model instead (#{caller_method})"
options[:model] = options.delete(:class_name)
end
if options.key?(:remote_name)
options[:remote_name] = options[:remote_name].to_sym
warn "+options[:remote_name]+ is deprecated, use :via instead (#{caller_method})"
options[:via] = options.delete(:remote_name)
end
if options.key?(:through)
assert_kind_of 'options[:through]', options[:through], Symbol, Module
end
[ :via, :inverse ].each do |key|
if options.key?(key)
assert_kind_of "options[#{key.inspect}]", options[key], Symbol, Associations::Relationship
end
end
# TODO: deprecate :child_key and :parent_key in favor of :source_key and
# :target_key (will mean something different for each relationship)
[ :child_key, :parent_key ].each do |key|
if options.key?(key) && !options[key].is_a?(Enumerable)
options[key] = Array(options[key])
end
end
if options.key?(:limit)
raise ArgumentError, '+options[:limit]+ should not be specified on a relationship'
end
end
# Dynamically defines reader method
#
# @api private
def create_relationship_reader(relationship)
name = relationship.name
reader_name = name.to_s
return if method_defined?(reader_name)
reader_visibility = relationship.reader_visibility
class_eval <<-RUBY, __FILE__, __LINE__ + 1
chainable do
#{reader_visibility}
def #{reader_name}(query = nil)
# TODO: when no query is passed in, return the results from
# the ivar directly. This will require that the ivar
# actually hold the resource/collection, and in the case
# of 1:1, the underlying collection is hidden in a
# private ivar, and the resource is in a known ivar
persisted_state.get(relationships[#{name.inspect}], query)
end
end
RUBY
end
# Dynamically defines writer method
#
# @api private
def create_relationship_writer(relationship)
name = relationship.name
writer_name = "#{name}="
return if method_defined?(writer_name)
writer_visibility = relationship.writer_visibility
class_eval <<-RUBY, __FILE__, __LINE__ + 1
chainable do
#{writer_visibility}
def #{writer_name}(target)
relationship = relationships[#{name.inspect}]
self.persisted_state = persisted_state.set(relationship, target)
persisted_state.get(relationship)
end
end
RUBY
end
chainable do
# @api public
def method_missing(method, *args, &block)
if relationship = relationships(repository_name)[method]
return Query::Path.new([ relationship ])
end
super
end
end
end # module Relationship
end # module Model
end # module DataMapper