Created
October 29, 2012 21:11
-
-
Save mrkvm/3976569 to your computer and use it in GitHub Desktop.
Ruby method to set a Redis key if it's not already defined using a Lua script.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'redis' | |
# Lua script to set a Redis key if it doesn't exist yet. | |
# Returns result of SET if key is not set, otherwise | |
# returns the previous value of the key. | |
SetScript = <<EOF | |
local val = redis.call('GET', KEYS[1]) | |
if val == false then | |
return redis.call('SET', KEYS[1], ARGV[1]) | |
end | |
return redis.call('GET', KEYS[1]) | |
EOF | |
def set_if_not_def(key, value) | |
Redis.new.eval SetScript, [key], [value] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Of course, this is a silly example given that Redis provides SETNX and HSETNX.