@@ -8,15 +8,10 @@ class CollectionSerializer
8
8
attr_reader :object , :root
9
9
10
10
def initialize ( resources , options = { } )
11
- @root = options [ :root ]
12
- @object = resources
13
-
11
+ @object = resources
12
+ @options = options
13
+ @root = options [ :root ]
14
14
serializer_context_class = options . fetch ( :serializer_context_class , ActiveModel ::Serializer )
15
-
16
- if resources . blank? && options [ :serializer ]
17
- @each_serializer = options [ :serializer ]
18
- end
19
-
20
15
@serializers = resources . map do |resource |
21
16
serializer_class = options . fetch ( :serializer ) { serializer_context_class . serializer_for ( resource ) }
22
17
@@ -32,9 +27,28 @@ def success?
32
27
true
33
28
end
34
29
30
+ # TODO: unify naming of root, json_key, and _type. Right now, a serializer's
31
+ # json_key comes from the root option or the object's model name, by default.
32
+ # But, if a dev defines a custom `json_key` method with an explicit value,
33
+ # we have no simple way to know that it is safe to call that instance method.
34
+ # (which is really a class property at this point, anyhow).
35
+ # rubocop:disable Metrics/CyclomaticComplexity
36
+ # Disabling cop since it's good to highlight the complexity of this method by
37
+ # including all the logic right here.
35
38
def json_key
36
- root || derived_root || guess_root || default_root
39
+ return root if root
40
+ # 1. get from options[:serializer] for empty resource collection
41
+ key = object . empty? &&
42
+ ( explicit_serializer_class = options [ :serializer ] ) &&
43
+ explicit_serializer_class . _type
44
+ # 2. get from first serializer instance in collection
45
+ key ||= ( serializer = serializers . first ) && serializer . json_key
46
+ # 3. get from collection name, if a named collection
47
+ key ||= object . respond_to? ( :name ) ? object . name && object . name . underscore : nil
48
+ # 4. key may be nil for empty collection and no serializer option
49
+ key && key . pluralize
37
50
end
51
+ # rubocop:enable Metrics/CyclomaticComplexity
38
52
39
53
def paginated?
40
54
object . respond_to? ( :current_page ) &&
@@ -44,21 +58,7 @@ def paginated?
44
58
45
59
protected
46
60
47
- attr_reader :serializers
48
-
49
- private
50
-
51
- def derived_root
52
- serializers . first . try ( :json_key ) . try ( :pluralize )
53
- end
54
-
55
- def default_root
56
- object . try ( :name ) . try ( :underscore ) . try ( :pluralize )
57
- end
58
-
59
- def guess_root
60
- @each_serializer . try ( :allocate ) . try ( :json_key ) . try ( :pluralize )
61
- end
61
+ attr_reader :serializers , :options
62
62
end
63
63
end
64
64
end
0 commit comments