lib/daybreak/db.rb in daybreak-0.0.4 vs lib/daybreak/db.rb in daybreak-0.1.0
- old
+ new
@@ -26,12 +26,11 @@
# @param [#to_s] key the key of the storage slot in the database
# @param value the value to store
# @param [Boolean] sync if true, sync this value immediately
def []=(key, value, sync = false)
key = key.to_s
- @writer.write(Record.new(key, serialize(value)))
- flush! if sync
+ write key, value, sync
@table[key] = value
end
alias_method :set, :"[]="
# set! flushes data immediately to disk.
@@ -39,10 +38,25 @@
# @param value the value to store
def set!(key, value)
set key, value, true
end
+ # Delete a key from the database
+ # @param [#to_s] key the key of the storage slot in the database
+ # @param [Boolean] sync if true, sync this deletion immediately
+ def delete(key, sync = false)
+ key = key.to_s
+ write key, '', sync, true
+ @table.delete key
+ end
+
+ # delete! immediately deletes the key on disk.
+ # @param [#to_s] key the key of the storage slot in the database
+ def delete!(key)
+ delete key, true
+ end
+
# Retrieve a value at key from the database. If the default value was specified
# when this database was created, that value will be set and returned. Aliased
# as <tt>get</tt>.
# @param [#to_s] key the value to retrieve from the database.
def [](key)
@@ -110,10 +124,11 @@
# Reset and empty the database file.
def empty!
@writer.truncate!
reset!
end
+ alias_method :clear, :empty!
# Force all queued commits to be written to disk.
def flush!
@writer.flush!
end
@@ -136,11 +151,11 @@
# Create a new temporary file
tmp_file = Tempfile.new File.basename(@file_name)
copy_db = self.class.new tmp_file.path
# Copy the database key by key into the temporary table
- each do |key, i|
+ each do |key|
copy_db.set(key, get(key))
end
copy_db.close!
# Empty this database
@@ -159,10 +174,21 @@
# Read all values from the log file. If you want to check for changed data
# call this again.
def read!
@reader.read do |record|
- @table[record.key] = parse record.data
+ if record.deleted?
+ @table.delete record.key
+ else
+ @table[record.key] = parse(record.data)
+ end
end
+ end
+
+ private
+
+ def write(key, value, sync = false, delete = false)
+ @writer.write(Record.new(key, serialize(value), delete))
+ flush! if sync
end
end
end