Clean nil and 'empty?' values in a data store prior to commiting

This commit is contained in:
Mitchell Hashimoto 2010-09-03 12:02:44 -07:00
parent b8a4188fa3
commit e4cb2749a1
2 changed files with 34 additions and 0 deletions

View File

@ -24,9 +24,34 @@ module Vagrant
def commit
return if !file_path
clean_nil_and_empties
File.open(file_path, "w") do |f|
f.write(to_json)
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

View File

@ -38,4 +38,13 @@ class DataStoreTest < Test::Unit::TestCase
assert_equal "changed", @klass.new(@db_file)[:foo]
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