@@ -14,8 +14,33 @@ class Serializer
14
14
include Configuration
15
15
include Associations
16
16
require 'active_model/serializer/adapter'
17
- Attribute = Struct . new ( :name , :reader ) do
17
+ class Attribute
18
18
delegate :call , to : :reader
19
+ attr_reader :name , :reader
20
+ def initialize ( name )
21
+ @name = name
22
+ @reader = nil
23
+ end
24
+
25
+ def self . build ( name , block )
26
+ if block
27
+ AttributeBlock . new ( name , block )
28
+ else
29
+ AttributeReader . new ( name )
30
+ end
31
+ end
32
+ end
33
+ class AttributeReader < Attribute
34
+ def initialize ( name )
35
+ super ( name )
36
+ @reader = -> ( instance ) { instance . read_attribute_for_serialization ( name ) }
37
+ end
38
+ end
39
+ class AttributeBlock < Attribute
40
+ def initialize ( name , block )
41
+ super ( name )
42
+ @reader = -> ( instance ) { instance . instance_eval ( &block ) }
43
+ end
19
44
end
20
45
21
46
# Matches
@@ -117,15 +142,7 @@ def self.attributes(*attrs)
117
142
# end
118
143
def self . attribute ( attr , options = { } , &block )
119
144
key = options . fetch ( :key , attr )
120
- reader = if block
121
- -> ( instance ) { instance . instance_eval ( &block ) }
122
- elsif _fragmented
123
- -> ( instance ) { instance . class . _fragmented . read_attribute_for_serialization ( attr ) }
124
- else
125
- -> ( instance ) { instance . read_attribute_for_serialization ( attr ) }
126
- end
127
-
128
- _attribute_mappings [ key ] = Attribute . new ( attr , reader )
145
+ _attribute_mappings [ key ] = Attribute . build ( attr , block )
129
146
end
130
147
131
148
# @api private
@@ -281,6 +298,8 @@ def attributes(requested_attrs = nil)
281
298
def read_attribute_for_serialization ( attr )
282
299
if _serializer_method_defined? ( attr )
283
300
send ( attr )
301
+ elsif self . class . _fragmented
302
+ self . class . _fragmented . read_attribute_for_serialization ( attr )
284
303
else
285
304
object . read_attribute_for_serialization ( attr )
286
305
end
0 commit comments