diff --git a/lib/action_controller/serialization.rb b/lib/action_controller/serialization.rb index e05c340b2..cafeae95d 100644 --- a/lib/action_controller/serialization.rb +++ b/lib/action_controller/serialization.rb @@ -6,6 +6,12 @@ module Serialization include ActionController::Renderers + RENDERER_METHODS = [ + :_render_option_json, + :_render_with_renderer_json, + :_render_option_xml, + :_render_with_renderer_xml + ] # Deprecated ADAPTER_OPTION_KEYS = ActiveModel::SerializableResource::ADAPTER_OPTION_KEYS @@ -45,7 +51,7 @@ def use_adapter? true end - [:_render_option_json, :_render_with_renderer_json].each do |renderer_method| + RENDERER_METHODS.each do |renderer_method| define_method renderer_method do |resource, options| options.fetch(:context) { options[:context] = request } serializable_resource = get_serializer(resource, options) diff --git a/lib/active_model/serializer/adapter.rb b/lib/active_model/serializer/adapter.rb index 1cbeb9b76..807db04ea 100644 --- a/lib/active_model/serializer/adapter.rb +++ b/lib/active_model/serializer/adapter.rb @@ -36,6 +36,10 @@ def as_json(options = nil) hash end + def to_xml(options = nil) + as_json(options).to_xml + end + def fragment_cache(*args) raise NotImplementedError, 'This is an abstract method. Should be implemented at the concrete adapter.' end diff --git a/test/action_controller/serialization_test.rb b/test/action_controller/serialization_test.rb index a5535fa6e..77e1ef14a 100644 --- a/test/action_controller/serialization_test.rb +++ b/test/action_controller/serialization_test.rb @@ -136,6 +136,13 @@ def render_fragment_changed_object_with_relationship render json: like end + def render_object_xml + profile = Profile.new(name: 'Name 1', description: 'Description 1', comments: 'Comments 1') + with_adapter :flatten_json do + render xml: profile + end + end + private def generate_cached_serializer(obj) @@ -420,6 +427,14 @@ def use_adapter? controller.get_serializer(Profile.new) }) end + + def test_render_object_xml + get :render_object_xml + + hash = Hash.from_xml(@response.body).each_value.first + assert_equal('application/xml', @response.content_type) + assert_equal({ 'name' => 'Name 1', 'description' => 'Description 1' }, hash) + end end end end