Skip to content

Commit eceb2d5

Browse files
committed
Refactor serializer attribute objects
1 parent 8804d75 commit eceb2d5

File tree

1 file changed

+29
-10
lines changed

1 file changed

+29
-10
lines changed

lib/active_model/serializer.rb

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,33 @@ class Serializer
1414
include Configuration
1515
include Associations
1616
require 'active_model/serializer/adapter'
17-
Attribute = Struct.new(:name, :reader) do
17+
class Attribute
1818
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
1944
end
2045

2146
# Matches
@@ -117,15 +142,7 @@ def self.attributes(*attrs)
117142
# end
118143
def self.attribute(attr, options = {}, &block)
119144
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)
129146
end
130147

131148
# @api private
@@ -281,6 +298,8 @@ def attributes(requested_attrs = nil)
281298
def read_attribute_for_serialization(attr)
282299
if _serializer_method_defined?(attr)
283300
send(attr)
301+
elsif self.class._fragmented
302+
self.class._fragmented.read_attribute_for_serialization(attr)
284303
else
285304
object.read_attribute_for_serialization(attr)
286305
end

0 commit comments

Comments
 (0)