From 07e544a703e542599c67a2c711834fa64e9f806d Mon Sep 17 00:00:00 2001 From: Sean Doyle Date: Mon, 20 Oct 2025 15:13:28 -0400 Subject: [PATCH] Validations: Decode errors with XmlFormat or JsonFormat Related to https://github.com/rails/activeresource/pull/441 This commit also adds the `remove_root = true` optional argument to the `JsonFormat` and `XmlFormat` modules' `#decode` method. The name and positional argument style draw direct inspiration from the `ActiveResource::Base#load` method's optional `remove_root = true` argument. The change is in support of replacing internal calls to `Hash.from_xml` and `ActiveSupport::JSON.decode`. Those method invocations are replaced with the appropriate format's `.decode` method. --- lib/active_resource/formats/json_format.rb | 5 +++-- lib/active_resource/formats/xml_format.rb | 5 +++-- lib/active_resource/validations.rb | 4 ++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/lib/active_resource/formats/json_format.rb b/lib/active_resource/formats/json_format.rb index 3bbe8da34a..7ca8c83944 100644 --- a/lib/active_resource/formats/json_format.rb +++ b/lib/active_resource/formats/json_format.rb @@ -19,9 +19,10 @@ def encode(resource, options = nil) resource.to_json(options) end - def decode(json) + def decode(json, remove_root = true) return nil if json.nil? - Formats.remove_root(ActiveSupport::JSON.decode(json)) + hash = ActiveSupport::JSON.decode(json) + remove_root ? Formats.remove_root(hash) : hash end end end diff --git a/lib/active_resource/formats/xml_format.rb b/lib/active_resource/formats/xml_format.rb index f86ab56115..3d314d04a3 100644 --- a/lib/active_resource/formats/xml_format.rb +++ b/lib/active_resource/formats/xml_format.rb @@ -19,8 +19,9 @@ def encode(resource, options = {}) resource.to_xml(options) end - def decode(xml) - Formats.remove_root(Hash.from_xml(xml)) + def decode(xml, remove_root = true) + hash = Hash.from_xml(xml) + remove_root ? Formats.remove_root(hash) : hash end end end diff --git a/lib/active_resource/validations.rb b/lib/active_resource/validations.rb index d1a63d9300..c9d2c0b6f8 100644 --- a/lib/active_resource/validations.rb +++ b/lib/active_resource/validations.rb @@ -54,14 +54,14 @@ def from_hash(messages, save_cache = false) # Grabs errors from a json response. def from_json(json, save_cache = false) - decoded = ActiveSupport::JSON.decode(json) || {} rescue {} + decoded = Formats[:json].decode(json, false) || {} rescue {} errors = decoded["errors"] || {} from_hash errors, save_cache end # Grabs errors from an XML response. def from_xml(xml, save_cache = false) - array = Array.wrap(Hash.from_xml(xml)["errors"]["error"]) rescue [] + array = Array.wrap(Formats[:xml].decode(xml, false)["errors"]["error"]) rescue [] from_array array, save_cache end end