@@ -5,37 +5,27 @@ module Attributes
5
5
6
6
included do
7
7
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 ||= { }
12
10
end
13
11
12
+ autoload :Attribute
13
+
14
14
# Return the +attributes+ of +object+ as presented
15
15
# by the serializer.
16
16
def attributes ( requested_attrs = nil , reload = false )
17
17
@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 )
30
21
end
31
22
end
32
23
end
33
24
34
25
module ClassMethods
35
26
def inherited ( base )
36
27
super
37
- base . _attribute_procs = _attribute_procs . dup
38
- base . _attribute_keys = _attribute_keys . dup
28
+ base . _attributes_data = _attributes_data . dup
39
29
end
40
30
41
31
# @example
@@ -62,26 +52,25 @@ def attributes(*attrs)
62
52
# object.edits.last(5)
63
53
# end
64
54
def attribute ( attr , options = { } , &block )
65
- _attribute_keys [ attr ] = options . fetch ( :key , attr )
66
- _attribute_procs [ attr ] = block
55
+ _attributes_data [ attr ] = Attribute . new ( attr , options . fetch ( :key , attr ) , block )
67
56
end
68
57
69
58
# @api private
70
59
# keys of attributes
71
60
# @see Serializer::attribute
72
61
def _attributes
73
- _attribute_keys . values
62
+ _attributes_data . values . map ( & :key )
74
63
end
75
64
76
65
# @api private
77
66
# maps attribute value to explict key name
78
67
# @see Serializer::attribute
79
68
# @see Adapter::FragmentCache#fragment_serializer
80
69
def _attributes_keys
81
- _attribute_keys
82
- . each_with_object ( { } ) do |( name , key ) , hash |
83
- next if key == name
84
- hash [ name ] = { key : key }
70
+ _attributes_data . values
71
+ . each_with_object ( { } ) do |attr , hash |
72
+ next if attr . key == attr . name
73
+ hash [ attr . name ] = { key : attr . key }
85
74
end
86
75
end
87
76
end
0 commit comments