Class: Pwnbus::Configdb::Db

Inherits:
Object
  • Object
show all
Defined in:
lib/pwnbus/configdb/db.rb

Overview

Database instance.

Defined Under Namespace

Classes: Proxy

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ Db

Database initialized with the contents of a file.

Args:

file:: File instance


18
19
20
21
22
# File 'lib/pwnbus/configdb/db.rb', line 18

def initialize(file)
  @data = YAML.load file
  @dirty = false
  @proxy = Proxy.new self, ''
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



11
12
13
# File 'lib/pwnbus/configdb/db.rb', line 11

def data
  @data
end

#proxyObject (readonly)

Returns the value of attribute proxy.



12
13
14
# File 'lib/pwnbus/configdb/db.rb', line 12

def proxy
  @proxy
end

Instance Method Details

#[](key) ⇒ Object

Reads a key from the database.

Args:

key:: string or symbol

Returns the value associated with the key, or nil if the key does not exist.



47
48
49
# File 'lib/pwnbus/configdb/db.rb', line 47

def [](key)
  @data[key.to_s]
end

#[]=(key, value) ⇒ Object

Inserts or updates a key in the database.

Args:

key:: string or symbol
value:: the value to be associated with the key

Returns value.



58
59
60
61
62
63
64
65
66
67
# File 'lib/pwnbus/configdb/db.rb', line 58

def []=(key, value)
  @dirty = true
  if value.nil?
    @data.delete key.to_s
  else
    @data[key.to_s] = (value.kind_of?(Numeric) || value.kind_of?(Symbol) ||
                       value == true || value == false) ? value : value.dup
  end
  value
end

#closeObject

Any future reads / writes will result in a crash.



37
38
39
# File 'lib/pwnbus/configdb/db.rb', line 37

def close
  @data = nil
end

#dirty?Boolean

True if the database contents has changed since the database has been open.

Returns:

  • (Boolean)


70
71
72
# File 'lib/pwnbus/configdb/db.rb', line 70

def dirty?
  @dirty
end

#proxy_get(key) ⇒ Object

Reads a key from the database, creating a proxy for inexistent keys.

Args:

key:: string or symbol

Returns the value associated with the key, or a database access proxy if the key doesn’t exist. This makes it possible to have .-separated keys, like db.user.name = ‘abc’.



82
83
84
85
# File 'lib/pwnbus/configdb/db.rb', line 82

def proxy_get(key)
  value = self[key]
  value.nil? ? Proxy.new(self, key + '.') : value
end

#proxy_set(key, value) ⇒ Object

Inserts or updates

Args:

key:: string or symbol
value:: the value to be associated with the key

Returns value.



94
95
96
# File 'lib/pwnbus/configdb/db.rb', line 94

def proxy_set(key, value)
  self[key] = value
end

#write(file) ⇒ Object

Writes the database contents to a file.

Args:

file:: File instance

Returns true.



30
31
32
33
34
# File 'lib/pwnbus/configdb/db.rb', line 30

def write(file)
  file.truncate 0
  YAML.dump @data, file
  true
end