@@ -13,9 +13,8 @@ module Associations
1313 DEFAULT_INCLUDE_TREE = ActiveModel ::Serializer ::IncludeTree . from_string ( '*' )
1414
1515 included do |base |
16- class << base
17- attr_accessor :_reflections
18- end
16+ base . class_attribute :_reflections
17+ base . _reflections ||= [ ]
1918
2019 extend ActiveSupport ::Autoload
2120 autoload :Association
@@ -28,8 +27,10 @@ class << base
2827 end
2928
3029 module ClassMethods
30+ # Serializers inherit _reflections.
3131 def inherited ( base )
32- base . _reflections = self . _reflections . try ( :dup ) || [ ]
32+ super
33+ base . _reflections = _reflections . dup
3334 end
3435
3536 # @param [Symbol] name of the association
@@ -39,8 +40,8 @@ def inherited(base)
3940 # @example
4041 # has_many :comments, serializer: CommentSummarySerializer
4142 #
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 )
4445 end
4546
4647 # @param [Symbol] name of the association
@@ -50,8 +51,8 @@ def has_many(name, options = {})
5051 # @example
5152 # belongs_to :author, serializer: AuthorSerializer
5253 #
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 )
5556 end
5657
5758 # @param [Symbol] name of the association
@@ -61,8 +62,8 @@ def belongs_to(name, options = {})
6162 # @example
6263 # has_one :author, serializer: AuthorSerializer
6364 #
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 )
6667 end
6768
6869 private
@@ -73,11 +74,15 @@ def has_one(name, options = {})
7374 #
7475 # @api private
7576 #
76- def associate ( reflection )
77+ def associate ( reflection , block )
7778 self . _reflections = _reflections . dup
7879
7980 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
8186 end unless method_defined? ( reflection . name )
8287
8388 self . _reflections << reflection
0 commit comments