From 1d4b27f60f97537c63ebd82c0aa34bb9fe69fcad Mon Sep 17 00:00:00 2001 From: Lucas Hosseini Date: Sun, 20 Dec 2015 15:56:32 +0100 Subject: [PATCH] Improve attribute value computation. --- lib/active_model/serializer/attributes.rb | 28 +++++++++++------------ 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/lib/active_model/serializer/attributes.rb b/lib/active_model/serializer/attributes.rb index 676e02e0..35263374 100644 --- a/lib/active_model/serializer/attributes.rb +++ b/lib/active_model/serializer/attributes.rb @@ -5,8 +5,8 @@ module ActiveModel included do with_options instance_writer: false, instance_reader: false do |serializer| - serializer.class_attribute :_attribute_mappings # @api private : maps attribute key names to names to names of implementing methods, @see #attribute - self._attribute_mappings ||= {} + serializer.class_attribute :_attribute_procs # @api private : maps attribute key names to names to names of implementing methods, @see #attribute + self._attribute_procs ||= {} serializer.class_attribute :_attribute_keys # @api private : maps attribute names to keys, @see #attribute self._attribute_keys ||= {} end @@ -17,7 +17,16 @@ module ActiveModel @attributes = nil if reload @attributes ||= self.class._attribute_keys.each_with_object({}) do |(name, key), hash| next unless requested_attrs.nil? || requested_attrs.include?(key) - hash[key] = self.class._attribute_mappings[name].call(self) + hash[key] = _attribute_value(name) + end + end + + # @api private + def _attribute_value(name) + if self.class._attribute_procs[name] + instance_eval(&self.class._attribute_procs[name]) + else + read_attribute_for_serialization(name) end end end @@ -25,7 +34,7 @@ module ActiveModel module ClassMethods def inherited(base) super - base._attribute_mappings = _attribute_mappings.dup + base._attribute_procs = _attribute_procs.dup base._attribute_keys = _attribute_keys.dup end @@ -54,16 +63,7 @@ module ActiveModel # end def attribute(attr, options = {}, &block) _attribute_keys[attr] = options.fetch(:key, attr) - _attribute_mappings[attr] = _attribute_mapping(attr, block) - end - - # @api private - def _attribute_mapping(name, block) - if block - ->(instance) { instance.instance_eval(&block) } - else - ->(instance) { instance.read_attribute_for_serialization(name) } - end + _attribute_procs[attr] = block end # @api private