From 07715c7415e4a5ecfb2b5d0de2ad6d59c97e1da8 Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Thu, 27 Apr 2023 14:35:26 +0200 Subject: [PATCH] Fix YAML serialization Ref: https://github.com/sporkmonger/addressable/pull/486 Following the introduction of `NONE` flags, `Addressable::URI` instance can no longer be correctly serialized with YAML. It appear to work, but `NONE` is serialized as `!ruby/object {}`, so when the YAML is parsed back, the attributes are assigned a distinct anonymous object. --- lib/addressable/uri.rb | 19 +++++++++++++++++++ spec/addressable/uri_spec.rb | 9 +++++++++ 2 files changed, 28 insertions(+) diff --git a/lib/addressable/uri.rb b/lib/addressable/uri.rb index 50ccdaf5..59fd32aa 100644 --- a/lib/addressable/uri.rb +++ b/lib/addressable/uri.rb @@ -2396,6 +2396,25 @@ def defer_validation @validation_deferred = false end + def encode_with(coder) + instance_variables.each do |ivar| + value = instance_variable_get(ivar) + if value != NONE + key = ivar.to_s.slice(1..-1) + coder[key] = value + end + end + nil + end + + def init_with(coder) + reset_ivs + coder.map.each do |key, value| + instance_variable_set("@#{key}", value) + end + nil + end + protected SELF_REF = '.' PARENT = '..' diff --git a/spec/addressable/uri_spec.rb b/spec/addressable/uri_spec.rb index c54fc3fb..0f985a93 100644 --- a/spec/addressable/uri_spec.rb +++ b/spec/addressable/uri_spec.rb @@ -20,6 +20,7 @@ require "addressable/uri" require "uri" require "ipaddr" +require "yaml" if !"".respond_to?("force_encoding") class String @@ -6799,3 +6800,11 @@ def to_str expect(res).to be nil end end + +describe Addressable::URI, "YAML safe loading" do + it "doesn't serialize anonymous objects" do + url = Addressable::URI.parse("http://example.com/") + payload = YAML.dump(url) + YAML.safe_load(payload, permitted_classes: [Addressable::URI]) + end +end