Class: Vagrant::DataStore

Inherits:
Util::HashWithIndifferentAccess show all
Defined in:
lib/vagrant/data_store.rb

Overview

The Vagrant data store is a key-value store which is persisted as JSON in a local file which is specified in the initializer. The data store itself is accessed via typical hash accessors: [] 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.

The data store is a hash with indifferent access, meaning that while all keys are persisted as strings in the JSON, you can access them back as either symbols or strings. Note that this is only true for the top-level data store. As soon as you set a hash inside the data store, unless you explicitly use a Util::HashWithIndifferentAccess, it will be a regular hash.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Util::HashWithIndifferentAccess

#[], #[]=, #delete, #key?, #merge, #merge!, #values_at

Constructor Details

#initialize(file_path) ⇒ DataStore

Returns a new instance of DataStore.



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/vagrant/data_store.rb', line 18

def initialize(file_path)
  @file_path = file_path
  return if !file_path

  raise Errors::DotfileIsDirectory if File.directory?(file_path)

  if File.exist?(file_path)
    File.open(file_path, "r") do |f|
      merge!(JSON.parse(f.read))
    end
  end
end

Instance Attribute Details

#file_pathObject (readonly)

Returns the value of attribute file_path.



16
17
18
# File 'lib/vagrant/data_store.rb', line 16

def file_path
  @file_path
end

Instance Method Details

#commitObject

Commits any changes to the data to disk. Even if the data hasn't changed, it will be reserialized and written to disk.



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/vagrant/data_store.rb', line 33

def commit
  return if !file_path

  clean_nil_and_empties

  if empty?
    # Delete the file since an empty data store is not useful
    File.delete(file_path) if File.file?(file_path)
  else
    File.open(file_path, "w") { |f| f.write(to_json) }
  end
end