@@ -8,15 +8,10 @@ class CollectionSerializer
88 attr_reader :object , :root
99
1010 def initialize ( resources , options = { } )
11- @root = options [ :root ]
12- @object = resources
13-
11+ @object = resources
12+ @options = options
13+ @root = options [ :root ]
1414 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-
2015 @serializers = resources . map do |resource |
2116 serializer_class = options . fetch ( :serializer ) { serializer_context_class . serializer_for ( resource ) }
2217
@@ -32,9 +27,28 @@ def success?
3227 true
3328 end
3429
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.
3538 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
3750 end
51+ # rubocop:enable Metrics/CyclomaticComplexity
3852
3953 def paginated?
4054 object . respond_to? ( :current_page ) &&
@@ -44,21 +58,7 @@ def paginated?
4458
4559 protected
4660
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
6262 end
6363 end
6464end
0 commit comments