Clean nil and 'empty?' values in a data store prior to commiting
This commit is contained in:
parent
b8a4188fa3
commit
e4cb2749a1
|
@ -24,9 +24,34 @@ module Vagrant
|
||||||
def commit
|
def commit
|
||||||
return if !file_path
|
return if !file_path
|
||||||
|
|
||||||
|
clean_nil_and_empties
|
||||||
File.open(file_path, "w") do |f|
|
File.open(file_path, "w") do |f|
|
||||||
f.write(to_json)
|
f.write(to_json)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
protected
|
||||||
|
|
||||||
|
# Removes the "nil" and "empty?" values from the hash (children
|
||||||
|
# included) so that the final output JSON is cleaner.
|
||||||
|
def clean_nil_and_empties(hash=self)
|
||||||
|
# Clean depth first
|
||||||
|
hash.each do |k, v|
|
||||||
|
clean_nil_and_empties(v) if v.is_a?(Hash)
|
||||||
|
end
|
||||||
|
|
||||||
|
# Clean ourselves, knowing that any children have already been
|
||||||
|
# cleaned up
|
||||||
|
bad_keys = hash.inject([]) do |acc, data|
|
||||||
|
k,v = data
|
||||||
|
acc.push(k) if v.nil?
|
||||||
|
acc.push(k) if v.respond_to?(:empty?) && v.empty?
|
||||||
|
acc
|
||||||
|
end
|
||||||
|
|
||||||
|
bad_keys.each do |key|
|
||||||
|
hash.delete(key)
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -38,4 +38,13 @@ class DataStoreTest < Test::Unit::TestCase
|
||||||
|
|
||||||
assert_equal "changed", @klass.new(@db_file)[:foo]
|
assert_equal "changed", @klass.new(@db_file)[:foo]
|
||||||
end
|
end
|
||||||
|
|
||||||
|
should "clean nil and empties if commit is called" do
|
||||||
|
@instance[:foo] = { :bar => nil }
|
||||||
|
@instance[:bar] = {}
|
||||||
|
@instance.commit
|
||||||
|
|
||||||
|
assert !@instance.has_key?(:foo)
|
||||||
|
assert !@instance.has_key?(:bar)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
Loading…
Reference in New Issue