class FileDb
Attributes
hash[RW]
path[RW]
Public Class Methods
new(path, default_value = {})
click to toggle source
# File lib/file_db.rb, line 5 def initialize(path, default_value = {}) @hash = default_value.dup @path = path self.open end
Public Instance Methods
[](key)
click to toggle source
# File lib/file_db.rb, line 57 def [](key) @hash[key] end
[]=(key, value)
click to toggle source
# File lib/file_db.rb, line 46 def []=(key, value) value = value.to_s # reload if boot is key to avoid initial change problem between threads # TODO: Refactoring config.dat handling between threads open if key == "boot" old = @hash[key.to_s] ret = @hash[key.to_s] = value save if old != value ret end
each(&block)
click to toggle source
# File lib/file_db.rb, line 28 def each(&block) @hash.each(&block) end
each_with_index(&block)
click to toggle source
# File lib/file_db.rb, line 32 def each_with_index(&block) @hash.each_with_index(&block) end
open()
click to toggle source
# File lib/file_db.rb, line 11 def open if File.exist?(@path) file = File.open(@path) self.parse(file.read) end ensure file.close if file end
parse(text)
click to toggle source
# File lib/file_db.rb, line 20 def parse(text) text.split("\n").compact.each do |line| key_value = line.split("=", 2) key, value = sanitize(key_value[0]), sanitize(key_value[1]) @hash[key] = value unless value.empty? end end
save()
click to toggle source
# File lib/file_db.rb, line 36 def save string = @hash.inject("") do |str, line| #|line_key, line_value| str << "#{line[0]}=#{line[1]}\n" end File.open(@path, "w") {|f| f.write(string) } true rescue => e false end
update_attributes(values = Hash.new)
click to toggle source
# File lib/file_db.rb, line 61 def update_attributes(values = Hash.new) values.each do |key, value| @hash[key.to_s] = value.to_s end save end
Private Instance Methods
sanitize(string)
click to toggle source
# File lib/file_db.rb, line 69 def sanitize(string) new_string = string.to_s.strip if new_string[0] == "\"" && new_string[-1] == "\"" new_string = new_string[1..-2] end new_string end