Class: Petruchio::Ring

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

Constant Summary collapse

INIT_LUA_SCRIPT =
"local key = KEYS[1]\nlocal size = tonumber(ARGV[1])\nlocal value = ARGV[2]\n\nif redis.call('EXISTS', key) == 0 then\n  for i=1,size do\n    redis.call('RPUSH', key, value)\n  end\nend\n"
RESIZE_LUA_SCRIPT =
"local key = KEYS[1]\nlocal size = redis.call(\"llen\", key)\nlocal new_size = tonumber(ARGV[1])\nlocal value = ARGV[2]\n\nif size > new_size then\n  redis.call('LTRIM', key, (size - new_size), (size - 1))\nelseif size < new_size then\n  for i = 1, (new_size - size) do\n    redis.call('RPUSH', key, value)\n  end\nend\n\nreturn redis.call('LLEN', key)\n"

Instance Method Summary collapse

Constructor Details

#initialize(redis, ring_name, size, initial_item) ⇒ Ring

Returns a new instance of Ring.



37
38
39
40
41
42
43
# File 'lib/petruchio.rb', line 37

def initialize(redis, ring_name, size, initial_item)
  @redis = redis
  @ring_name = ring_name
  @initial_item = initial_item

  @redis.eval(INIT_LUA_SCRIPT, [@ring_name], [size, @initial_item])
end

Instance Method Details

#pop ⇒ Object



50
51
52
# File 'lib/petruchio.rb', line 50

def pop
  @redis.lpop @ring_name
end

#push(item) ⇒ Object



54
55
56
# File 'lib/petruchio.rb', line 54

def push(item)
  @redis.rpush @ring_name, item
end

#push_pop(item) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/petruchio.rb', line 58

def push_pop(item)
  popped, *rest =
    T.let(
      @redis.multi do |transaction|
        transaction.lpop @ring_name
        transaction.rpush @ring_name, item
      end,
      [String, T.untyped]
    )

  popped
end

#read ⇒ Object



71
72
73
# File 'lib/petruchio.rb', line 71

def read
  @redis.lrange(@ring_name, 0, -1)
end

#resize(new_size) ⇒ Object



45
46
47
48
# File 'lib/petruchio.rb', line 45

def resize(new_size)
  # returns the new size
  @redis.eval RESIZE_LUA_SCRIPT, [@ring_name], [new_size, @initial_item]
end