Skip to content

Commit 9db188b

Browse files
committed
Add to YamlLoader
1 parent a8bdc10 commit 9db188b

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

lib/test/test_yaml_loader.rb

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,49 @@
77

88
class TestYamlLoader < Minitest::Test
99

10+
def test_remove
11+
yaml = <<~YAML
12+
base:
13+
key1: value1
14+
key2: value2
15+
16+
child:
17+
$mref: "#/base"
18+
$remove: key2
19+
key3: value3
20+
YAML
21+
22+
f = Tempfile.new("yml")
23+
f.write(yaml)
24+
f.flush
25+
26+
doc = YamlLoader.load(f.path)
27+
assert_equal({ "key1" => "value1", "key3" => "value3" }, doc["child"])
28+
end
29+
30+
def test_multiple_remove
31+
yaml = <<~YAML
32+
base:
33+
key1: value1
34+
key2: value2
35+
key3: value3
36+
37+
child:
38+
$mref: "#/base"
39+
$remove:
40+
- key2
41+
- key3
42+
key4: value4
43+
YAML
44+
45+
f = Tempfile.new("yml")
46+
f.write(yaml)
47+
f.flush
48+
49+
doc = YamlLoader.load(f.path)
50+
assert_equal({ "key1" => "value1", "key4" => "value4" }, doc["child"])
51+
end
52+
1053
def test_that_spurious_recursive_mref_works
1154
yaml = <<~YAML
1255
base:

lib/yaml_loader.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ def self.expand(filename, obj, yaml_opts = {})
1414

1515
return obj.map { |v| expand(filename, v, yaml_opts) } if obj.is_a?(Array)
1616

17+
new_obj =
1718
if obj.keys.include?("$ref")
1819
# according JSON Reference, all keys except $ref are ignored
1920
relative_path = obj["$ref"].split("#")[0]
@@ -85,6 +86,7 @@ def self.expand(filename, obj, yaml_opts = {})
8586

8687
new_obj[key] = expand(filename, value, yaml_opts)
8788
end
89+
8890
new_obj
8991
else
9092
obj_keys = obj.keys
@@ -95,6 +97,16 @@ def self.expand(filename, obj, yaml_opts = {})
9597
end
9698
obj
9799
end
100+
101+
obj_keys = new_obj.keys
102+
if obj_keys.include? "$remove"
103+
remove_keys = obj["$remove"].is_a?(Array) ? obj["$remove"] : [obj["$remove"]]
104+
remove_keys.each do |key|
105+
new_obj.delete(key)
106+
end
107+
end
108+
new_obj.delete("$remove")
109+
new_obj
98110
end
99111

100112
# load a YAML file and expand any $ref/$mref references

0 commit comments

Comments
 (0)