Class: Twitterpunch::Queue

Inherits:
Object
  • Object
show all
Defined in:
lib/twitterpunch/queue.rb

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Queue

Returns a new instance of Queue.



2
3
4
5
6
# File 'lib/twitterpunch/queue.rb', line 2

def initialize(config)
  @config = config
  @file   = config[:queue][:file]
  @ttl    = config[:queue][:ttl]
end

Instance Method Details

#load(file) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/twitterpunch/queue.rb', line 39

def load(file)
  queue   = YAML.load(file.read) rescue {}
  queue ||= {}

  # forcibly expire anything that's too old.
  queue.select { |k,v| (Time.now - k) < @ttl }
end

#popObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/twitterpunch/queue.rb', line 8

def pop
  message = nil
  File.open(@file, 'r+') do |file|
    file.flock(File::LOCK_EX)
    queue = load(file)

    unless queue.empty?
      if RUBY_VERSION < "1.9.3"
        message = queue[queue.keys.sort.first]
      else
        message = queue.shift[1]
      end
    end

    save(file, queue)
  end
  message
end

#push(message) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/twitterpunch/queue.rb', line 27

def push(message)
  return unless message.is_a? String
  return if message.empty?
  File.open(@file, 'r+') do |file|
    file.flock(File::LOCK_EX)

    queue = load(file)
    queue[Time.now] = message
    save(file, queue)
  end
end

#save(file, queue) ⇒ Object



47
48
49
50
51
# File 'lib/twitterpunch/queue.rb', line 47

def save(file, queue)
  file.rewind
  file.truncate 0
  file.write(queue.to_yaml)
end