diff --git a/lib/active_model_serializers/adapter/attributes.rb b/lib/active_model_serializers/adapter/attributes.rb index 3372e2be8..8964f0bc8 100644 --- a/lib/active_model_serializers/adapter/attributes.rb +++ b/lib/active_model_serializers/adapter/attributes.rb @@ -5,7 +5,7 @@ module Adapter class Attributes < Base def initialize(*) super - instance_options[:fieldset] ||= ActiveModel::Serializer::Fieldset.new(fields_to_fieldset(instance_options.delete(:fields))) + instance_options[:fieldset] ||= fields_to_fieldset(instance_options.delete(:fields)) end def serializable_hash(options = nil) @@ -29,7 +29,7 @@ def fields_to_fieldset(fields) else fail ArgumentError, "Unknown conversion of fields to fieldset: '#{field.inspect}' in '#{fields.inspect}'" end end - relationship_fields.merge!(serializer.json_key.to_sym => resource_fields) + ActiveModel::Serializer::Fieldset.new(relationship_fields.merge!(serializer.json_key.to_sym => resource_fields)) end end end diff --git a/lib/active_model_serializers/adapter/json_api.rb b/lib/active_model_serializers/adapter/json_api.rb index 83c75ea82..9570483ef 100644 --- a/lib/active_model_serializers/adapter/json_api.rb +++ b/lib/active_model_serializers/adapter/json_api.rb @@ -53,7 +53,7 @@ def self.fragment_cache(cached_hash, non_cached_hash, root = true) def initialize(serializer, options = {}) super @include_directive = JSONAPI::IncludeDirective.new(options[:include], allow_wildcard: true) - @fieldset = options[:fieldset] || ActiveModel::Serializer::Fieldset.new(options.delete(:fields)) + @fieldset = options[:fieldset] || fields_to_fieldset(options.delete(:fields)) end # {http://jsonapi.org/format/#crud Requests are transactional, i.e. success or failure} @@ -335,6 +335,7 @@ def resource_object_for(serializer, include_slice = {}) resource_object end + # rubocop:disable Metrics/CyclomaticComplexity def data_for(serializer, include_slice) data = serializer.fetch(self) do resource_object = ResourceIdentifier.new(serializer, instance_options).as_json @@ -348,11 +349,12 @@ def data_for(serializer, include_slice) data.tap do |resource_object| next if resource_object.nil? # NOTE(BF): the attributes are cached above, separately from the relationships, below. - requested_associations = fieldset.fields_for(resource_object[:type]) || '*' + requested_associations = (fieldset && fieldset.fields_for(resource_object[:type])) || '*' relationships = relationships_for(serializer, requested_associations, include_slice) resource_object[:relationships] = relationships if relationships.any? end end + # rubocop:enable Metrics/CyclomaticComplexity # {http://jsonapi.org/format/#document-resource-object-relationships Document Resource Object Relationship} # relationships @@ -529,6 +531,12 @@ def pagination_links_for(serializer) def meta_for(serializer) Meta.new(serializer).as_json end + + def fields_to_fieldset(fields) + return fields if fields.nil? + + ActiveModel::Serializer::Fieldset.new(fields) + end end end end