lib/daybreak/writer.rb in daybreak-0.0.1 vs lib/daybreak/writer.rb in daybreak-0.0.2

- old
+ new

@@ -2,15 +2,13 @@ # Writer's handle the actually fiddly task of committing data to disk. # They have a Worker instance that writes in a select loop. class Writer # Open up the file, ready it for binary and nonblocking writing. def initialize(file) - @fd = File.open file, 'a' - @fd.binmode + @file = file - f = @fd.fcntl(Fcntl::F_GETFL, 0) - @fd.fcntl(Fcntl::F_SETFL, Fcntl::O_NONBLOCK | f) + open! @worker = Worker.new(@fd) end # Send a record to the workers queue. @@ -26,21 +24,31 @@ # Flush pending commits, and restart the worker. def flush! @worker.flush! end - # Finish writing and close the file descriptor + # Finish writing and close the file descriptor. def close! finish! @fd.close end # Truncate the file. def truncate! + flush! @fd.truncate(0) + open! end private + + def open! + @fd = File.open @file, 'a' + @fd.binmode + + f = @fd.fcntl(Fcntl::F_GETFL, 0) + @fd.fcntl(Fcntl::F_SETFL, Fcntl::O_NONBLOCK | f) + end # Workers handle the actual fiddly bits of asynchronous io and # and handle background writes. class Worker include Locking