Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix incorrect deserialization of some legacy formats #49

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions lib/ostruct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -435,9 +435,10 @@ def encode_with(coder) # :nodoc:
@table.each_pair do |key, value|
coder[key.to_s] = value
end
if @table.size == 1 && @table.key?(:table) # support for legacy format
# in the very unlikely case of a single entry called 'table'
coder['legacy_support!'] = true # add a bogus second entry

# ensure data isn't corrupted on reload if it looks like the legacy format
if @table.size == 1 && @table.key?(:table) || @table.size == 2 && [:modifiable, :table].all? { |x| @table.key?(x) }
coder['legacy_support!'] = true # add a bogus entry to change the size
end
end

Expand All @@ -446,12 +447,12 @@ def encode_with(coder) # :nodoc:
#
def init_with(coder) # :nodoc:
h = coder.map
if h.size == 1 # support for legacy format
key, val = h.first
if key == 'table'
h = val
end

# support for legacy format
if h.size == 1 && h.key?('table') || h.size == 2 && %w[modifiable table].all? { |x| h.key?(x) }
h = h['table']
end

update_to_values!(h)
end

Expand Down
9 changes: 9 additions & 0 deletions test/ostruct/test_ostruct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,15 @@ def test_legacy_yaml
assert_equal({foo: 42}, YAML.safe_load(YAML.dump(o), permitted_classes: [Symbol, OpenStruct]).table)
end if RUBY_VERSION >= '2.6'

def test_legacy_yaml_2
s = "--- !ruby/object:OpenStruct\ntable:\n :foo: 42\nmodifiable: true\n"
o = YAML.safe_load(s, permitted_classes: [Symbol, OpenStruct])
assert_equal(42, o.foo)

o = OpenStruct.new(table: {foo: 42})
assert_equal({foo: 42}, YAML.safe_load(YAML.dump(o), permitted_classes: [Symbol, OpenStruct]).table)
end if RUBY_VERSION >= '2.6'

def test_yaml
h = {name: "John Smith", age: 70, pension: 300.42}
yaml = "--- !ruby/object:OpenStruct\nname: John Smith\nage: 70\npension: 300.42\n"
Expand Down