@@ -13,9 +13,8 @@ module Associations
13
13
DEFAULT_INCLUDE_TREE = ActiveModel ::Serializer ::IncludeTree . from_string ( '*' )
14
14
15
15
included do |base |
16
- class << base
17
- attr_accessor :_reflections
18
- end
16
+ base . class_attribute :_reflections
17
+ base . _reflections ||= [ ]
19
18
20
19
extend ActiveSupport ::Autoload
21
20
autoload :Association
@@ -28,8 +27,10 @@ class << base
28
27
end
29
28
30
29
module ClassMethods
30
+ # Serializers inherit _reflections.
31
31
def inherited ( base )
32
- base . _reflections = self . _reflections . try ( :dup ) || [ ]
32
+ super
33
+ base . _reflections = _reflections . dup
33
34
end
34
35
35
36
# @param [Symbol] name of the association
@@ -39,8 +40,8 @@ def inherited(base)
39
40
# @example
40
41
# has_many :comments, serializer: CommentSummarySerializer
41
42
#
42
- def has_many ( name , options = { } )
43
- associate HasManyReflection . new ( name , options )
43
+ def has_many ( name , options = { } , & block )
44
+ associate ( HasManyReflection . new ( name , options ) , block )
44
45
end
45
46
46
47
# @param [Symbol] name of the association
@@ -50,8 +51,8 @@ def has_many(name, options = {})
50
51
# @example
51
52
# belongs_to :author, serializer: AuthorSerializer
52
53
#
53
- def belongs_to ( name , options = { } )
54
- associate BelongsToReflection . new ( name , options )
54
+ def belongs_to ( name , options = { } , & block )
55
+ associate ( BelongsToReflection . new ( name , options ) , block )
55
56
end
56
57
57
58
# @param [Symbol] name of the association
@@ -61,8 +62,8 @@ def belongs_to(name, options = {})
61
62
# @example
62
63
# has_one :author, serializer: AuthorSerializer
63
64
#
64
- def has_one ( name , options = { } )
65
- associate HasOneReflection . new ( name , options )
65
+ def has_one ( name , options = { } , & block )
66
+ associate ( HasOneReflection . new ( name , options ) , block )
66
67
end
67
68
68
69
private
@@ -73,11 +74,15 @@ def has_one(name, options = {})
73
74
#
74
75
# @api private
75
76
#
76
- def associate ( reflection )
77
+ def associate ( reflection , block )
77
78
self . _reflections = _reflections . dup
78
79
79
80
define_method reflection . name do
80
- object . send reflection . name
81
+ if block_given?
82
+ instance_eval ( &block )
83
+ else
84
+ object . send reflection . name
85
+ end
81
86
end unless method_defined? ( reflection . name )
82
87
83
88
self . _reflections << reflection
0 commit comments