Sha256: 0addeeaf663a4ffedb608b878a43db5ed093e0b6bba624b29e4570ec06b625b7

Contents?: true

Size: 775 Bytes

Versions: 2

Compression:

Stored size: 775 Bytes

Contents

class FileQueue
	
  def initialize(file_name)
    @file_name = file_name
  end

  def push(obj)
    safe_open('a') do |file|
      file.write(obj + "\n")
    end
  end

  alias << push
	
  def pop
    value = nil
    rest = nil
    safe_open('r') do |file|
      value = file.gets
      rest = file.read
    end
    safe_open('w+') do |file|
      file.write(rest)
    end
    value
  end

  def length
    count = 0
    safe_open('r') do |file|
      count = file.read.count("\n")
    end
    count
  end

  def empty?
    return length == 0
  end

  def clear
    safe_open('w') do |file| end
  end
	
  private
  def safe_open(mode)
    File.open(@file_name, mode) do |file|
      file.flock(File::LOCK_EX)
      yield file
      file.flock(File::LOCK_UN)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
filequeue-0.0.2 file_queue.rb
filequeue-0.0.1 file_queue.rb