You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.3 KiB
Ruby
56 lines
1.3 KiB
Ruby
require 'fileutils'
|
|
|
|
class Database
|
|
def initialize(file)
|
|
@file = file
|
|
File.open(@file, 'w').write unless File.exist? @file
|
|
lines = File.readlines(@file) if File.exist? @file
|
|
FileUtils.touch(@file) unless File.exist? @file
|
|
lines.count = 0 unless File.exist? @file
|
|
@start = 0
|
|
@end = lines.count
|
|
end
|
|
|
|
def message(msg)
|
|
puts "#{@file}: #{msg}"
|
|
end
|
|
|
|
def get(key)
|
|
lines= File.readlines(@file)
|
|
eval('[' + lines.join() + ']').map { |hash|
|
|
hash[key]
|
|
}
|
|
end
|
|
|
|
def prepend(key, val)
|
|
lines = File.readlines(@file)
|
|
lines.insert(@start, "{:key => '#{key}', :value => '#{val}'},\n")
|
|
File.write(@file, lines.join)
|
|
end
|
|
|
|
def append(key, val)
|
|
message "added #{key} => #{val}"
|
|
lines = File.readlines(@file)
|
|
lines.insert(@end, "{:key => '#{key}', :value => '#{val}'},\n")
|
|
File.write(@file, lines.join)
|
|
end
|
|
|
|
def <<(hash)
|
|
lines = File.readlines(@file)
|
|
lines.insert(@end, "{:key => '#{hash[:key]}', :value => '#{hash[:value]}'},\n")
|
|
File.write(@file, lines.join)
|
|
end
|
|
|
|
def [](i)
|
|
lines = File.readlines(@file)
|
|
return eval('[' + lines.join() + ']')[i]
|
|
#return eval lines[i]
|
|
end
|
|
|
|
def []=(i, hash)
|
|
lines = File.readlines(@file)
|
|
lines.insert(i, "{:key => '#{hash[:key]}', :value => '#{hash[:value]}'},\n")
|
|
File.write(@file, lines.join)
|
|
end
|
|
end
|