Skip to content

Commit dfe1626

Browse files
committed
Generalize detection of serializable resource with errors
1 parent 0ba944d commit dfe1626

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

lib/active_model/serializable_resource.rb

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,13 @@ def initialize(resource, options = {})
1616
@resource = resource
1717
@adapter_opts, @serializer_opts =
1818
options.partition { |k, _| ADAPTER_OPTION_KEYS.include? k }.map { |h| Hash[h] }
19+
end
1920

20-
# TECHDEBT: clean up single vs. collection of resources
21+
def errors?
2122
if resource.respond_to?(:each)
22-
if resource.any? { |elem| elem.respond_to?(:errors) && !elem.errors.empty? }
23-
@serializer_opts[:serializer] = ActiveModel::Serializer::ErrorSerializer
24-
@adapter_opts[:adapter] = :'json_api/error'
25-
end
23+
resource.any? { |elem| elem.respond_to?(:errors) && !elem.errors.empty? }
2624
else
27-
if resource.respond_to?(:errors) && !resource.errors.empty?
28-
@serializer_opts[:serializer] = ActiveModel::Serializer::ErrorSerializer
29-
@adapter_opts[:adapter] = :'json_api/error'
30-
end
25+
resource.respond_to?(:errors) && !resource.errors.empty?
3126
end
3227
end
3328

@@ -44,7 +39,11 @@ def serialization_scope_name=(scope_name)
4439
end
4540

4641
def adapter
47-
@adapter ||= ActiveModelSerializers::Adapter.create(serializer_instance, adapter_opts)
42+
@adapter ||=
43+
begin
44+
adapter_opts[:adapter] = :'json_api/error' if errors?
45+
ActiveModelSerializers::Adapter.create(serializer_instance, adapter_opts)
46+
end
4847
end
4948
alias_method :adapter_instance, :adapter
5049

@@ -59,6 +58,7 @@ def serializer
5958
@serializer ||=
6059
begin
6160
@serializer = serializer_opts.delete(:serializer)
61+
@serializer = ActiveModel::Serializer::ErrorSerializer if errors?
6262
@serializer ||= ActiveModel::Serializer.serializer_for(resource)
6363

6464
if serializer_opts.key?(:each_serializer)

0 commit comments

Comments
 (0)