Class: VPNMaker::KeyDB

Inherits:
Object
  • Object
show all
Defined in:
lib/vpnmaker/key_db.rb

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ KeyDB

Returns a new instance of KeyDB.



3
4
5
6
7
# File 'lib/vpnmaker/key_db.rb', line 3

def initialize(path)
  @path = path
  @db = File.exists?(path) ? YAML.load_file(path) : {}
  @touched = false
end

Instance Method Details

#[](k) ⇒ Object



9
# File 'lib/vpnmaker/key_db.rb', line 9

def [](k); @db[k]; end

#[]=(k, v) ⇒ Object



11
12
13
14
15
# File 'lib/vpnmaker/key_db.rb', line 11

def []=(k, v)
  @db[k] = v
  @db[:modified] = Time.now
  @touched = true
end

#data(k) ⇒ Object



36
37
38
# File 'lib/vpnmaker/key_db.rb', line 36

def data(k)
  File.exists?(data_path(k)) ? File.read(data_path(k)) : nil
end

#data_path(k) ⇒ Object



25
26
27
# File 'lib/vpnmaker/key_db.rb', line 25

def data_path(k)
  File.join(File.dirname(@path), self.datadir, k)
end

#datadirObject



23
# File 'lib/vpnmaker/key_db.rb', line 23

def datadir; self[:datadir]; end

#disk_versionObject



40
41
42
# File 'lib/vpnmaker/key_db.rb', line 40

def disk_version
  File.exists?(@path) ? YAML.load_file(@path)[:version] : 0
end

#dump(k, v, overwrite = false) ⇒ Object



29
30
31
32
33
34
# File 'lib/vpnmaker/key_db.rb', line 29

def dump(k, v, overwrite=false)
  p = data_path(k)
  raise "#{k} already exists" if File.exists?(p) && !overwrite
  File.open(p, 'w') {|f| f.write(v)}
  @touched = true
end

#syncObject



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/vpnmaker/key_db.rb', line 44

def sync
  if disk_version == @db[:version]
    if @touched
      FileUtils.mkdir_p(File.dirname(@path) + "/" + self.datadir)
      @db[:version] += 1
      File.open(@path, 'w') {|f| f.write(@db.to_yaml)}
      true
    else
      false
    end
  else
    raise "Disk version of #{@path} (#{disk_version}) != loaded version (#{@db[:version]}). " + \
    "Try reloading and making your changes again."
  end
end

#touched!Object



17
18
19
20
# File 'lib/vpnmaker/key_db.rb', line 17

def touched!
  @touched = true
  @db[:modified] = Time.now
end

#versionObject



60
# File 'lib/vpnmaker/key_db.rb', line 60

def version; @db[:version]; end