diff --git a/lib/vagrant/data_store.rb b/lib/vagrant/data_store.rb index 3b6766d71..70487678c 100644 --- a/lib/vagrant/data_store.rb +++ b/lib/vagrant/data_store.rb @@ -5,33 +5,24 @@ module Vagrant # and `[]=`. If a key is set to `nil`, then it is removed from the # datastore. The data store is only updated on disk when {commit} # is called on the data store itself. - class DataStore + class DataStore < Hash attr_reader :file_path def initialize(file_path) @file_path = file_path File.open(file_path, "r") do |f| - @data = JSON.parse(f.read) + merge!(JSON.parse(f.read)) end - end - - # Returns the value associated with the `key` in the data - # store. - def [](key) - @data[key] - end - - # Sets the value in the data store. - def []=(key, value) - @data[key] = value + rescue Errno::ENOENT + clear end # Commits any changes to the data to disk. Even if the data # hasn't changed, it will be reserialized and written to disk. def commit File.open(file_path, "w") do |f| - f.write(@data.to_json) + f.write(to_json) end end end diff --git a/lib/vagrant/environment.rb b/lib/vagrant/environment.rb index 06842ca56..4ed09c2f5 100644 --- a/lib/vagrant/environment.rb +++ b/lib/vagrant/environment.rb @@ -151,6 +151,14 @@ module Vagrant end end + # Loads (on initial access) and reads data from the local data + # store. This file is always at the root path as the file "~/.vagrant" + # and contains a JSON dump of a hash. See {DataStore} for more + # information. + def local_data + @local_data ||= DataStore.new(dotfile_path) + end + #--------------------------------------------------------------- # Load Methods #--------------------------------------------------------------- diff --git a/test/vagrant/data_store_test.rb b/test/vagrant/data_store_test.rb index cb927c9f2..79ac1d333 100644 --- a/test/vagrant/data_store_test.rb +++ b/test/vagrant/data_store_test.rb @@ -14,6 +14,10 @@ class DataStoreTest < Test::Unit::TestCase File.delete(@db_file) end + should "just be an empty hash if file doesn't exist" do + assert @klass.new("NEvERNENVENRNE").empty? + end + should "read the data" do assert_equal @initial_data["foo"], @instance["foo"] end diff --git a/test/vagrant/environment_test.rb b/test/vagrant/environment_test.rb index 5f4990898..f1e7b05de 100644 --- a/test/vagrant/environment_test.rb +++ b/test/vagrant/environment_test.rb @@ -223,6 +223,20 @@ class EnvironmentTest < Test::Unit::TestCase end end + context "local data" do + setup do + @env = mock_environment + end + + should "lazy load the data store only once" do + result = mock("result") + Vagrant::DataStore.expects(:new).with(@env.dotfile_path).returns(result).once + assert_equal result, @env.local_data + assert_equal result, @env.local_data + assert_equal result, @env.local_data + end + end + context "loading" do setup do @env = mock_environment