Skip to content

Instantly share code, notes, and snippets.

@eljojo
Created April 29, 2014 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eljojo/11397116 to your computer and use it in GitHub Desktop.
Save eljojo/11397116 to your computer and use it in GitHub Desktop.
simple redis queue. it might have bugs.
class SimpleQueue
def initialize(name)
@name = name.to_sym
end
def push(items)
return unless items.present?
items = [items] unless items.is_a?(Array)
with_redis do |redis|
redis.sadd(redis_key, items.map(&:to_s))
end
end
def pop(count = 1)
l = length
count = l if count > l
with_redis do |redis|
count.times.map do
redis.spop(redis_key)
end
end
end
def length
with_redis do |redis|
redis.scard(redis_key)
end
end
private
delegate :with_redis, to: :class
def redis_key
@redis_key ||= "simple_queue:#{@name}"
end
class << self
def redis_pool
if defined?(Sidekiq)
Sidekiq.redis_pool
else
raise "We currently use sidekiq's connection pool :("
end
end
def with_redis(&block)
raise ArgumentError, "requires a block" if !block
redis_pool.with(&block)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment