Skip to content

Commit

Permalink
Simplify code
Browse files Browse the repository at this point in the history
and don't raise on duplicate key
  • Loading branch information
svanhesteren committed Jul 15, 2024
1 parent de3eb54 commit a97b8f7
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 18 deletions.
21 changes: 6 additions & 15 deletions lib/eyaml/util.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,16 @@ def pretty_yaml(some_hash)
def with_deep_deundescored_keys(hash)
hash.each_with_object({}) do |pair, total|
key, value = pair
case value
when Hash
child_hash = with_deep_deundescored_keys(value)

if key.start_with?("_")
raise KeyError, "De-underscored key '#{key[1..]}' already exists." if total.key?(key[1..])
value = with_deep_deundescored_keys(value) if value.is_a?(Hash)

total[key[1..]] = child_hash
end
if key.start_with?("_")
deunderscored_key = key[1..]

total[key] = child_hash
else
if key.start_with?("_")
raise KeyError, "De-underscored key '#{key[1..]}' already exists." if total.key?(key[1..])

total[key[1..]] = value
end
total[key] = value
total[deunderscored_key] = value unless total.key?(deunderscored_key)
end

total[key] = value
end
end
end
Expand Down
6 changes: 3 additions & 3 deletions spec/eyaml/util_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@
expect(EYAML::Util.with_deep_deundescored_keys(yaml_without_prefix)).to eq({"a"=>"1", "b"=>"2", "c"=>{"d"=>"3", "_d"=>"3"}, "_c"=>{"d"=>"3", "_d"=>"3"}})
end

it "will raise when a de-underscored key already exists" do
yaml_without_prefix = YAML.load_file(fixtures_root.join("pretty.yml")).merge!("_b" => "X")
it "does not overwrite the not underscored key when we have an underscored key" do
yaml_without_prefix = YAML.load_file(fixtures_root.join("pretty.yml")).merge("_b" => "X")

expect { EYAML::Util.with_deep_deundescored_keys(yaml_without_prefix) }.to raise_error(KeyError)
expect(EYAML::Util.with_deep_deundescored_keys(yaml_without_prefix)).to eq({"a"=>"1", "b"=>"2", "_b"=>"X", "c"=>{"d"=>"3", "_d"=>"3"}, "_c"=>{"d"=>"3", "_d"=>"3"}})
end
end
end

0 comments on commit a97b8f7

Please sign in to comment.