This repository has been archived by the owner on Apr 17, 2018. It is now read-only.
/
one_to_one.rb
74 lines (62 loc) · 2.3 KB
/
one_to_one.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
module DataMapper
module Associations
module OneToOne #:nodoc:
class Relationship < Associations::Relationship
%w[ public protected private ].map do |visibility|
superclass.send("#{visibility}_instance_methods", false).each do |method|
undef_method method unless method.to_s == 'initialize'
end
end
# Loads (if necessary) and returns association target
# for given source
#
# @api semipublic
def get(source, other_query = nil)
assert_kind_of 'source', source, source_model
return unless loaded?(source) || source_key.get(source).all? { |value| !value.nil? }
relationship.get(source, other_query).first
end
# Sets and returns association target
# for given source
#
# @api semipublic
def set(source, target)
assert_kind_of 'source', source, source_model
assert_kind_of 'target', target, target_model, Hash, NilClass
relationship.set(source, [ target ].compact).first
end
# TODO: document
# @api public
def kind_of?(klass)
super || relationship.kind_of?(klass)
end
# TODO: document
# @api public
def instance_of?(klass)
super || relationship.instance_of?(klass)
end
# TODO: document
# @api public
def respond_to?(method, include_private = false)
super || relationship.respond_to?(method, include_private)
end
private
attr_reader :relationship
# Initializes the relationship. Always assumes target model class is
# a camel cased association name.
#
# @api semipublic
def initialize(name, target_model, source_model, options = {})
klass = options.key?(:through) ? ManyToMany::Relationship : OneToMany::Relationship
target_model ||= Extlib::Inflection.camelize(name).freeze
@relationship = klass.new(name, target_model, source_model, options)
end
# TODO: document
# @api private
def method_missing(method, *args, &block)
relationship.send(method, *args, &block)
end
end # class Relationship
end # module HasOne
end # module Associations
end # module DataMapper