Skip to content

Commit

Permalink
Improve attribute value computation.
Browse files Browse the repository at this point in the history
  • Loading branch information
beauby committed Dec 20, 2015
1 parent 0d3fe56 commit 32eb5ea
Showing 1 changed file with 14 additions and 14 deletions.
28 changes: 14 additions & 14 deletions lib/active_model/serializer/attributes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ module Attributes

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
Expand All @@ -17,15 +17,24 @@ def attributes(requested_attrs = nil, reload = false)
@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

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

Expand Down Expand Up @@ -54,16 +63,7 @@ def attributes(*attrs)
# 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
Expand Down

0 comments on commit 32eb5ea

Please sign in to comment.