class Coordinator::RedisQueue

Public Class Methods

new(name) click to toggle source
# File lib/coordinator/redis_queue.rb, line 5
def initialize(name)
  @queue_name = "#{name}-queue"
  @capacity_name = "#{name}-capacity"
  raise Coordinator::Error, "'Redis.current' not set" unless Redis.current
  @redis = Redis.current
end

Public Instance Methods

capacity() click to toggle source
# File lib/coordinator/redis_queue.rb, line 42
def capacity
  data = @redis.get(@capacity_name)
  deserialize(data)
end
capacity=(capacity) click to toggle source
# File lib/coordinator/redis_queue.rb, line 47
def capacity=(capacity)
  @redis.set(@capacity_name, capacity)
end
full?() click to toggle source
# File lib/coordinator/redis_queue.rb, line 55
def full?
  capacity && capacity <= length
end
items() click to toggle source
# File lib/coordinator/redis_queue.rb, line 51
def items
  serialized_items.map { |i| deserialize(i) }
end
left_push(item) click to toggle source
# File lib/coordinator/redis_queue.rb, line 18
def left_push(item)
  data = serialize(item)
  @redis.lpush(@queue_name, data) unless serialized_items.include?(data)
end
length() click to toggle source
# File lib/coordinator/redis_queue.rb, line 38
def length
  @redis.llen(@queue_name)
end
peek() click to toggle source
# File lib/coordinator/redis_queue.rb, line 33
def peek
  data = @redis.lrange(@queue_name, 0, 0).first
  deserialize(data)
end
pop() click to toggle source
# File lib/coordinator/redis_queue.rb, line 23
def pop
  data = @redis.lpop(@queue_name)
  deserialize(data)
end
push(item) click to toggle source
# File lib/coordinator/redis_queue.rb, line 12
def push(item)
  return false if full?
  data = serialize(item)
  @redis.rpush(@queue_name, data) unless serialized_items.include?(data)
end
remove(item) click to toggle source
# File lib/coordinator/redis_queue.rb, line 28
def remove(item)
  data = serialize(item)
  @redis.lrem(@queue_name, 1, data) == 1
end

Private Instance Methods

deserialize(item) click to toggle source
# File lib/coordinator/redis_queue.rb, line 69
def deserialize(item)
  return item if item.nil?
  return item.to_i if item.to_i.to_s == item
  begin
    JSON::parse(item)
  rescue JSON::ParserError
    item # regular string
  end
end
serialize(item) click to toggle source
# File lib/coordinator/redis_queue.rb, line 65
def serialize(item)
  item.is_a?(String) ? item : item.to_json
end
serialized_items() click to toggle source
# File lib/coordinator/redis_queue.rb, line 61
def serialized_items
  @redis.lrange(@queue_name, 0, length)
end