@@ -5,37 +5,27 @@ module Attributes
55
66 included do
77 with_options instance_writer : false , instance_reader : false do |serializer |
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 ||= { }
10- serializer . class_attribute :_attribute_keys # @api private : maps attribute names to keys, @see #attribute
11- self . _attribute_keys ||= { }
8+ serializer . class_attribute :_attributes_data # @api private
9+ self . _attributes_data ||= { }
1210 end
1311
12+ autoload :Attribute
13+
1414 # Return the +attributes+ of +object+ as presented
1515 # by the serializer.
1616 def attributes ( requested_attrs = nil , reload = false )
1717 @attributes = nil if reload
18- @attributes ||= self . class . _attribute_keys . each_with_object ( { } ) do |( name , key ) , hash |
19- next unless requested_attrs . nil? || requested_attrs . include? ( key )
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 )
18+ @attributes ||= self . class . _attributes_data . values . each_with_object ( { } ) do |attr , hash |
19+ next unless requested_attrs . nil? || requested_attrs . include? ( attr . key )
20+ hash [ attr . key ] = attr . value ( self )
3021 end
3122 end
3223 end
3324
3425 module ClassMethods
3526 def inherited ( base )
3627 super
37- base . _attribute_procs = _attribute_procs . dup
38- base . _attribute_keys = _attribute_keys . dup
28+ base . _attributes_data = _attributes_data . dup
3929 end
4030
4131 # @example
@@ -62,26 +52,26 @@ def attributes(*attrs)
6252 # object.edits.last(5)
6353 # end
6454 def attribute ( attr , options = { } , &block )
65- _attribute_keys [ attr ] = options . fetch ( :key , attr )
66- _attribute_procs [ attr ] = block
55+ key = options . fetch ( :key , attr )
56+ _attributes_data [ attr ] = Attribute . new ( attr , key , block )
6757 end
6858
6959 # @api private
7060 # keys of attributes
7161 # @see Serializer::attribute
7262 def _attributes
73- _attribute_keys . values
63+ _attributes_data . values . map ( & :key )
7464 end
7565
7666 # @api private
7767 # maps attribute value to explict key name
7868 # @see Serializer::attribute
7969 # @see Adapter::FragmentCache#fragment_serializer
8070 def _attributes_keys
81- _attribute_keys
82- . each_with_object ( { } ) do |( name , key ) , hash |
83- next if key == name
84- hash [ name ] = { key : key }
71+ _attributes_data . values
72+ . each_with_object ( { } ) do |attr , hash |
73+ next if attr . key == attr . name
74+ hash [ attr . name ] = { key : attr . key }
8575 end
8676 end
8777 end
0 commit comments