Class: FileDb

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, default_value = {}) ⇒ FileDb

Returns a new instance of FileDb.



5
6
7
8
9
# File 'lib/file_db.rb', line 5

def initialize(path, default_value = {})
  @hash = default_value.dup
  @path = path
  self.open
end

Instance Attribute Details

#hashObject

Returns the value of attribute hash.



3
4
5
# File 'lib/file_db.rb', line 3

def hash
  @hash
end

#pathObject

Returns the value of attribute path.



3
4
5
# File 'lib/file_db.rb', line 3

def path
  @path
end

Instance Method Details

#[](key) ⇒ Object



57
58
59
# File 'lib/file_db.rb', line 57

def [](key)
  @hash[key]
end

#[]=(key, value) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# 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) ⇒ Object



28
29
30
# File 'lib/file_db.rb', line 28

def each(&block)
  @hash.each(&block)
end

#each_with_index(&block) ⇒ Object



32
33
34
# File 'lib/file_db.rb', line 32

def each_with_index(&block)
  @hash.each_with_index(&block)
end

#openObject



11
12
13
14
15
16
17
18
# 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) ⇒ Object



20
21
22
23
24
25
26
# 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

#saveObject



36
37
38
39
40
41
42
43
44
# 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) ⇒ Object



61
62
63
64
65
66
# 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