Skip to content

Commit

Permalink
Fix YAML serialization (#508)
Browse files Browse the repository at this point in the history
Ref: #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.

Co-authored-by: Jean Boussier <jean.boussier@gmail.com>
  • Loading branch information
casperisfine and byroot committed May 19, 2023
1 parent e91b64e commit 736c42a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/addressable/uri.rb
Expand Up @@ -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 = '..'
Expand Down
8 changes: 8 additions & 0 deletions spec/addressable/uri_spec.rb
Expand Up @@ -20,6 +20,7 @@
require "addressable/uri"
require "uri"
require "ipaddr"
require "yaml"

if !"".respond_to?("force_encoding")
class String
Expand Down Expand Up @@ -6799,3 +6800,10 @@ 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/")
expect(YAML.dump(url)).to_not include("!ruby/object {}")
end
end

0 comments on commit 736c42a

Please sign in to comment.