diff --git a/CHANGELOG.md b/CHANGELOG.md index 06534b3de..e4e451e4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ Breaking changes: Features: +- [#1616](https://github.com/rails-api/active_model_serializers/pull/1616) SerializableResource handles no serializer like controller. (@bf4) - [#1574](https://github.com/rails-api/active_model_serializers/pull/1574) Provide key translation. (@remear) - [#1494](https://github.com/rails-api/active_model_serializers/pull/1494) Make serializers serializalbe (using the Attributes adapter by default). (@bf4) diff --git a/lib/action_controller/serialization.rb b/lib/action_controller/serialization.rb index cc7b8ba7d..ff21b8316 100644 --- a/lib/action_controller/serialization.rb +++ b/lib/action_controller/serialization.rb @@ -33,20 +33,12 @@ def get_serializer(resource, options = {}) options[:adapter] = false end serializable_resource = ActiveModel::SerializableResource.new(resource, options) - if serializable_resource.serializer? - serializable_resource.serialization_scope ||= serialization_scope - serializable_resource.serialization_scope_name = _serialization_scope - begin - # Necessary to ensure we have an adapter for the serializable resource - # after it has been figured. - # TODO: This logic should be less opaque and probably moved into the SerializableResource. - serializable_resource.tap(&:adapter) - rescue ActiveModel::Serializer::CollectionSerializer::NoSerializerError - resource - end - else - resource - end + serializable_resource.serialization_scope ||= serialization_scope + serializable_resource.serialization_scope_name = _serialization_scope + # For compatibility with the JSON renderer: `json.to_json(options) if json.is_a?(String)`. + # Otherwise, since `serializable_resource` is not a string, the renderer would call + # `to_json` on a String and given odd results, such as `"".to_json #=> '""'` + serializable_resource.adapter.is_a?(String) ? serializable_resource.adapter : serializable_resource end # Deprecated diff --git a/lib/active_model/serializable_resource.rb b/lib/active_model/serializable_resource.rb index bf0e36f18..642e6fb04 100644 --- a/lib/active_model/serializable_resource.rb +++ b/lib/active_model/serializable_resource.rb @@ -30,11 +30,19 @@ def serialization_scope_name=(scope_name) serializer_opts[:scope_name] = scope_name end + # NOTE: if no adapter is available, returns the resource itself. def adapter - @adapter ||= ActiveModelSerializers::Adapter.create(serializer_instance, adapter_opts) + @adapter ||= find_adapter end alias adapter_instance adapter + def find_adapter + return resource unless serializer? + ActiveModelSerializers::Adapter.create(serializer_instance, adapter_opts) + rescue ActiveModel::Serializer::CollectionSerializer::NoSerializerError + resource + end + def serializer_instance @serializer_instance ||= serializer.new(resource, serializer_opts) end