/
model_reflection.rb
100 lines (83 loc) · 2.63 KB
/
model_reflection.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
require 'delegate'
module Shoulda
module Matchers
module ActiveRecord
module AssociationMatchers
# @private
class ModelReflection < SimpleDelegator
def initialize(reflection)
super(reflection)
@reflection = reflection
@subject = reflection.active_record
end
def associated_class
reflection.klass
end
def polymorphic?
reflection.options[:polymorphic]
end
def through?
reflection.options[:through]
end
def join_table_name
join_table_name =
if has_and_belongs_to_many_name_table_name
has_and_belongs_to_many_name_table_name
else
reflection.join_table
end
join_table_name.to_s
end
def association_relation(related_instance)
relation = associated_class.all
if reflection.scope
# Source: AR::Associations::AssociationScope#eval_scope
relation.instance_exec(related_instance, &reflection.scope)
else
relation
end
end
def foreign_key
if has_and_belongs_to_many_reflection
has_and_belongs_to_many_reflection.foreign_key
elsif reflection.respond_to?(:foreign_key)
reflection.foreign_key
else
reflection.primary_key_name
end
end
def association_foreign_key
if has_and_belongs_to_many_reflection
join_model = has_and_belongs_to_many_reflection.options[:class]
join_model.right_reflection.foreign_key
else
reflection.association_foreign_key
end
end
def validate_inverse_of_through_association!
if through?
reflection.check_validity!
end
end
def has_and_belongs_to_many_name
reflection.options[:through]
end
protected
attr_reader :reflection, :subject
private
def has_and_belongs_to_many_name_table_name
if has_and_belongs_to_many_reflection
has_and_belongs_to_many_reflection.table_name
end
end
def has_and_belongs_to_many_reflection
@_has_and_belongs_to_many_reflection ||=
if has_and_belongs_to_many_name
@subject.reflect_on_association(has_and_belongs_to_many_name)
end
end
end
end
end
end
end