@@ -12,11 +12,11 @@ module Associations
12
12
13
13
DEFAULT_INCLUDE_TREE = ActiveModel ::Serializer ::IncludeTree . from_string ( '*' )
14
14
15
- included do | base |
16
- base . class_attribute :serialized_associations , instance_writer : false # @api public: maps association name to 'Reflection' instance
17
- base . serialized_associations ||= { }
18
- base . class_attribute : _reflections, instance_writer : false
19
- base . _reflections ||= [ ]
15
+ included do
16
+ with_options instance_writer : false , instance_reader : true do | serializer |
17
+ serializer . class_attribute :_reflections
18
+ self . _reflections ||= [ ]
19
+ end
20
20
21
21
extend ActiveSupport ::Autoload
22
22
autoload :Association
@@ -29,7 +29,6 @@ module Associations
29
29
end
30
30
31
31
module ClassMethods
32
- # Serializers inherit _reflections.
33
32
def inherited ( base )
34
33
super
35
34
base . _reflections = _reflections . dup
@@ -43,7 +42,7 @@ def inherited(base)
43
42
# has_many :comments, serializer: CommentSummarySerializer
44
43
#
45
44
def has_many ( name , options = { } , &block )
46
- associate ( HasManyReflection . new ( name , options ) , block )
45
+ associate ( HasManyReflection . new ( name , options , block ) )
47
46
end
48
47
49
48
# @param [Symbol] name of the association
@@ -54,7 +53,7 @@ def has_many(name, options = {}, &block)
54
53
# belongs_to :author, serializer: AuthorSerializer
55
54
#
56
55
def belongs_to ( name , options = { } , &block )
57
- associate ( BelongsToReflection . new ( name , options ) , block )
56
+ associate ( BelongsToReflection . new ( name , options , block ) )
58
57
end
59
58
60
59
# @param [Symbol] name of the association
@@ -65,7 +64,7 @@ def belongs_to(name, options = {}, &block)
65
64
# has_one :author, serializer: AuthorSerializer
66
65
#
67
66
def has_one ( name , options = { } , &block )
68
- associate ( HasOneReflection . new ( name , options ) , block )
67
+ associate ( HasOneReflection . new ( name , options , block ) )
69
68
end
70
69
71
70
private
@@ -76,20 +75,9 @@ def has_one(name, options = {}, &block)
76
75
#
77
76
# @api private
78
77
#
79
- def associate ( reflection , block )
78
+ def associate ( reflection )
80
79
self . _reflections = _reflections . dup
81
80
82
- reflection_name = reflection . name
83
- if block
84
- serialized_associations [ reflection_name ] = -> ( instance ) { instance . instance_eval ( &block ) }
85
- else
86
- serialized_associations [ reflection_name ] = -> ( instance ) { instance . object . send ( reflection_name ) }
87
- end
88
-
89
- define_method reflection_name do
90
- serialized_associations [ reflection_name ] . call ( self )
91
- end unless method_defined? ( reflection_name )
92
-
93
81
self . _reflections << reflection
94
82
end
95
83
end
0 commit comments