From 3fa11160356ad569b903ce5355a572fc2ffa5670 Mon Sep 17 00:00:00 2001 From: Guillermo Iguaran Date: Tue, 14 Oct 2014 11:33:06 -0500 Subject: [PATCH 1/2] Include root by default in JSON-API serializers --- lib/active_model/serializer/adapter/json_api.rb | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/active_model/serializer/adapter/json_api.rb b/lib/active_model/serializer/adapter/json_api.rb index 56399b35c..76340613b 100644 --- a/lib/active_model/serializer/adapter/json_api.rb +++ b/lib/active_model/serializer/adapter/json_api.rb @@ -2,6 +2,11 @@ module ActiveModel class Serializer class Adapter class JsonApi < Adapter + def initialize(serializer, options = {}) + super + serializer.root ||= true + end + def serializable_hash(opts = {}) @hash = serializer.attributes From b91a86b401efdc77923cd0595b6f4a1de5befbb6 Mon Sep 17 00:00:00 2001 From: Guillermo Iguaran Date: Tue, 14 Oct 2014 12:42:21 -0500 Subject: [PATCH 2/2] Add test for serialization for adapters with root by default --- test/action_controller/serialization_test.rb | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/test/action_controller/serialization_test.rb b/test/action_controller/serialization_test.rb index 085ed6877..dcfd9ea54 100644 --- a/test/action_controller/serialization_test.rb +++ b/test/action_controller/serialization_test.rb @@ -13,6 +13,16 @@ def render_using_custom_root @profile = Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' }) render json: @profile, root: "custom_root" end + + def render_using_default_adapter_root + old_adapter = ActiveModel::Serializer.config.adapter + # JSON-API adapter sets root by default + ActiveModel::Serializer.config.adapter = ActiveModel::Serializer::Adapter::JsonApi + @profile = Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' }) + render json: @profile + ensure + ActiveModel::Serializer.config.adapter = old_adapter + end end tests MyController @@ -31,6 +41,13 @@ def test_render_using_custom_root assert_equal 'application/json', @response.content_type assert_equal '{"custom_root":{"name":"Name 1","description":"Description 1"}}', @response.body end + + def test_render_using_default_root + get :render_using_default_adapter_root + + assert_equal 'application/json', @response.content_type + assert_equal '{"profile":{"name":"Name 1","description":"Description 1"}}', @response.body + end end end end