Skip to content

Instantly share code, notes, and snippets.

@sadasant
Forked from scalone/file_db.rb
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sadasant/4ccfb67870873d046a2a to your computer and use it in GitHub Desktop.
Save sadasant/4ccfb67870873d046a2a to your computer and use it in GitHub Desktop.
class FileDb < Hash
attr_accessor :path
def initialize
super
end
def self.open(path)
f = self.new
f.open(path)
f
end
def open(path)
@path = path
if File.exist?(path)
file = File.open(path, "r")
self.parse(file.read)
end
ensure
file.close if file
end
def parse(text)
text.each_line do |line|
line = line[0..-2] if line[-1] == "\n" # This seems to be necessary
key_value = line.split("=")
self[key_value[0]] = key_value[1]
end
end
def save
file_new = File.open(@path, "w+")
self.each do |line_key, line_value|
file_new.puts("#{line_key}=#{line_value}")
end
file_new.close
end
end
config = FileDb.open("config.dat")
config['apn'] = 'claro.com.br'
config['user'] = 'claro.com.br'
config['pass'] = 'claro.com.br'
config.save
puts config['apn']
puts config['user']
puts config['pass']
# reload/new
config = FileDb.open("config.dat")
puts config['apn']
puts config['user']
puts config['pass']
config['apn'] = 'tim.com.br'
config['user'] = 'tim.com.br'
config['pass'] = 'tim.com.br'
config.save
# reload/new
config = FileDb.open("config.dat")
puts config['apn']
puts config['user']
puts config['pass']
while true
odd = FileDb.new
odd.open("odd")
even = FileDb.open("even")
odd_count = odd["count"] || 1
even_count = even["count"] || 2
IO.display(0, 0, "#{odd.path} #{odd_count}")
IO.display(1, 0, "#{even.path} #{even_count}")
odd["count"] = odd_count.to_i+2
even["count"] = even_count.to_i+2
odd.save
even.save
IO.read_key
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment