Skip to content

Commit 32eb5ea

Browse files
committed
Improve attribute value computation.
1 parent 0d3fe56 commit 32eb5ea

File tree

1 file changed

+14
-14
lines changed

1 file changed

+14
-14
lines changed

lib/active_model/serializer/attributes.rb

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ module Attributes
55

66
included do
77
with_options instance_writer: false, instance_reader: false do |serializer|
8-
serializer.class_attribute :_attribute_mappings # @api private : maps attribute key names to names to names of implementing methods, @see #attribute
9-
self._attribute_mappings ||= {}
8+
serializer.class_attribute :_attribute_procs # @api private : maps attribute key names to names to names of implementing methods, @see #attribute
9+
self._attribute_procs ||= {}
1010
serializer.class_attribute :_attribute_keys # @api private : maps attribute names to keys, @see #attribute
1111
self._attribute_keys ||= {}
1212
end
@@ -17,15 +17,24 @@ def attributes(requested_attrs = nil, reload = false)
1717
@attributes = nil if reload
1818
@attributes ||= self.class._attribute_keys.each_with_object({}) do |(name, key), hash|
1919
next unless requested_attrs.nil? || requested_attrs.include?(key)
20-
hash[key] = self.class._attribute_mappings[name].call(self)
20+
hash[key] = _attribute_value(name)
21+
end
22+
end
23+
24+
# @api private
25+
def _attribute_value(name)
26+
if self.class._attribute_procs[name]
27+
instance_eval(&self.class._attribute_procs[name])
28+
else
29+
read_attribute_for_serialization(name)
2130
end
2231
end
2332
end
2433

2534
module ClassMethods
2635
def inherited(base)
2736
super
28-
base._attribute_mappings = _attribute_mappings.dup
37+
base._attribute_procs = _attribute_procs.dup
2938
base._attribute_keys = _attribute_keys.dup
3039
end
3140

@@ -54,16 +63,7 @@ def attributes(*attrs)
5463
# end
5564
def attribute(attr, options = {}, &block)
5665
_attribute_keys[attr] = options.fetch(:key, attr)
57-
_attribute_mappings[attr] = _attribute_mapping(attr, block)
58-
end
59-
60-
# @api private
61-
def _attribute_mapping(name, block)
62-
if block
63-
->(instance) { instance.instance_eval(&block) }
64-
else
65-
->(instance) { instance.read_attribute_for_serialization(name) }
66-
end
66+
_attribute_procs[attr] = block
6767
end
6868

6969
# @api private

0 commit comments

Comments
 (0)