class FileQueue
Constants
- DELAY_RANGE
- FileLockError
Attributes
delimiter[RW]
file_name[RW]
lock_timeout[RW]
Public Class Methods
new(file_name, delimiter="\n", lock_timeout: 10)
click to toggle source
# File lib/filequeue.rb, line 6 def initialize(file_name, delimiter="\n", lock_timeout: 10) @delimiter = delimiter @file_name = file_name @lock_timeout = lock_timeout end
Public Instance Methods
clear()
click to toggle source
# File lib/filequeue.rb, line 50 def clear safe_open 'w' do |file| end end
empty?()
click to toggle source
# File lib/filequeue.rb, line 46 def empty? return length == 0 end
length()
click to toggle source
# File lib/filequeue.rb, line 35 def length count = 0 unless(File.exist?(@file_name)) return 0 end safe_open 'r' do |file| count = file.read.count @delimiter end count end
pop()
click to toggle source
# File lib/filequeue.rb, line 23 def pop value = nil safe_open 'r+' do |file| value = file.gets @delimiter rest = file.read file.rewind file.truncate(0) file.write(rest) end value ? value[0..-(@delimiter.length) - 1] : nil end
push(obj)
click to toggle source
# File lib/filequeue.rb, line 12 def push(obj) if obj.match Regexp.new @delimiter raise "Queue objects cannot contain the queue delimiter" end safe_open 'a' do |file| file.write(obj + @delimiter) end end
Also aliased as: <<
Protected Instance Methods
lock(file)
click to toggle source
Locks the queue file for exclusive access. This will gives up after `lock_timeout` seconds.
Raises `FileLockError` if unable to acquire a lock.
Return is undefined.
# File lib/filequeue.rb, line 71 def lock(file) deadline = (Time.now + lock_timeout) until Time.now >= deadline || lock_acquired = file.flock(File::LOCK_NB|File::LOCK_EX) sleep(rand(DELAY_RANGE)) end (raise FileLockError, "Queue file appears to be permanently locked") unless lock_acquired end
safe_open(mode) { |file| ... }
click to toggle source
# File lib/filequeue.rb, line 56 def safe_open(mode) File.open(@file_name, mode) do |file| lock file yield file end end