Class: Nodectl::Database

Inherits:
Object
  • Object
show all
Defined in:
lib/nodectl/database.rb

Constant Summary collapse

LoadError =
Class.new(StandardError)
DumpError =
Class.new(StandardError)

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ Database

Returns a new instance of Database.



5
6
7
# File 'lib/nodectl/database.rb', line 5

def initialize(file_path)
  @db = DBM.open(file_path, 0666, DBM::WRCREAT)
end

Instance Method Details

#[](key) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/nodectl/database.rb', line 25

def [](key)
  blob = @db[key]

  if blob
    load(blob)
  else
    nil
  end
end

#[]=(key, value) ⇒ Object



35
36
37
38
39
# File 'lib/nodectl/database.rb', line 35

def []=(key, value)
  @db[key] = Marshal.dump(value)
rescue TypeError => e
  raise LoadError, "marshal dump error for key '#{key}' and value '#{value}': #{e.message}"
end

#fetch(key, default = nil) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/nodectl/database.rb', line 13

def fetch(key, default = nil)
  blob = @db[key]

  if blob
    load(blob)
  elsif default
    default
  else
    raise LoadError, "key not found: '#{key}'"
  end
end

#resetObject



9
10
11
# File 'lib/nodectl/database.rb', line 9

def reset
  @db.clear
end