Class: Tootsie::FileSystemQueue

Inherits:
Object
  • Object
show all
Defined in:
lib/tootsie/queues/file_system_queue.rb

Overview

A simple, naive queue implementation that stores items as JSON files in the file system.

Instance Method Summary collapse

Constructor Details

#initialize(directory) ⇒ FileSystemQueue

Returns a new instance of FileSystemQueue.



11
12
13
14
# File 'lib/tootsie/queues/file_system_queue.rb', line 11

def initialize(directory)
  @directory = directory
  FileUtils.mkdir_p(@directory)
end

Instance Method Details

#countObject



16
17
18
# File 'lib/tootsie/queues/file_system_queue.rb', line 16

def count
  Dir.glob(File.join(@directory, "*.json")).length
end

#pop(options = {}) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/tootsie/queues/file_system_queue.rb', line 28

def pop(options = {})
  loop do
    lock do
      file_name = Dir.glob(File.join(@directory, "*.json")).sort.first
      if file_name
        item = JSON.parse(File.read(file_name))
        FileUtils.rm(file_name)
        return item
      end
    end
    if options[:wait]
      sleep(1.0)
    else
      return nil
    end
  end
end

#push(item) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/tootsie/queues/file_system_queue.rb', line 20

def push(item)
  Tempfile.open('tootsie') do |tempfile|
    tempfile << item.to_json
    tempfile.close
    FileUtils.mv(tempfile.path, File.join(@directory, "#{Time.now.to_f}.json"))
  end
end