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



52
53
54
# File 'lib/file_db.rb', line 52

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

#[]=(key, value) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/file_db.rb', line 44

def []=(key, value)
  value = value.to_s
  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

#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



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/file_db.rb', line 32

def save
  file_new = File.open(@path, "w+")
  @hash.each do |line_key, line_value|
    file_new.puts("#{line_key}=#{line_value}")
  end
  true
rescue
  false
ensure
  file_new.close
end

#update_attributes(values = Hash.new) ⇒ Object



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

def update_attributes(values = Hash.new)
  values.each do |key, value|
    @hash[key.to_s] = value.to_s
  end
  save
end