From e4cb2749a1246422f8928c54d4692884c3d1ff35 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Fri, 3 Sep 2010 12:02:44 -0700 Subject: [PATCH] Clean nil and 'empty?' values in a data store prior to commiting --- lib/vagrant/data_store.rb | 25 +++++++++++++++++++++++++ test/vagrant/data_store_test.rb | 9 +++++++++ 2 files changed, 34 insertions(+) diff --git a/lib/vagrant/data_store.rb b/lib/vagrant/data_store.rb index c88f98c2e..f3e69f93a 100644 --- a/lib/vagrant/data_store.rb +++ b/lib/vagrant/data_store.rb @@ -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 diff --git a/test/vagrant/data_store_test.rb b/test/vagrant/data_store_test.rb index b9a0d59e6..53616a5ee 100644 --- a/test/vagrant/data_store_test.rb +++ b/test/vagrant/data_store_test.rb @@ -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