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
|
# File 'lib/redundancy/utils.rb', line 9
def self.cache_column klass, association, attribute, options
local_klass = klass
reflection = get_reflection local_klass, association
raise ArgumentError, "BelongsTo or HasOne reflection required" unless
[:has_one, :belongs_to].include? reflection.macro
foreign_key = reflection.foreign_key
remote_klass = reflection.klass
inverse_association = get_inverse_association local_klass, remote_klass, reflection.options
cache_column = options[:cache_column] || :"#{association}_#{attribute}"
case reflection.macro
when :belongs_to
local_klass.redundancies << UpdateColumn.new(
source: { association: association, attribute: attribute },
dest: { association: nil, attribute: cache_column },
change_if: foreign_key, klass: local_klass
)
when :has_one
if reflection.through_reflection
through_reflection = reflection.through_reflection
if through_reflection.through_reflection
raise ArgumentError, "Multi level has_one through reflection is not support yet!"
end
through_foreign_key = through_reflection.foreign_key
through_remote_klass = through_reflection.klass
through_association = reflection.source_reflection_name
through_inverse_association = get_inverse_association local_klass, through_remote_klass
case through_reflection.macro
when :belongs_to
local_klass.redundancies << UpdateColumn.new(
source: { association: association, attribute: attribute },
dest: { association: nil, attribute: cache_column },
change_if: through_foreign_key, klass: local_klass
)
when :has_one
raise ArgumentError, "has_one through has_one reflection is not support yet!"
end
through_remote_klass.redundancies << UpdateColumn.new(
source: { association: through_association, attribute: attribute },
dest: { association: through_inverse_association, attribute: cache_column },
change_if: foreign_key, klass: through_remote_klass
)
else
remote_klass.redundancies << UpdateColumnWithPrev.new(
source: { association: nil, attribute: attribute, nil_unless: foreign_key, default: options[:default] },
dest: { klass: local_klass, foreign_key: foreign_key, association: inverse_association, attribute: cache_column },
change_if: foreign_key, klass: remote_klass
)
end
end
remote_klass.redundancies << UpdateColumn.new(
source: { association: nil, attribute: attribute },
dest: { association: inverse_association, attribute: cache_column },
change_if: attribute, klass: remote_klass, update: true
)
end
|