Skip to content

Instantly share code, notes, and snippets.

@mrkvm
Created October 29, 2012 21:11
Show Gist options
  • Save mrkvm/3976569 to your computer and use it in GitHub Desktop.
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.
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
@mrkvm
Copy link
Author

mrkvm commented Oct 30, 2012

Of course, this is a silly example given that Redis provides SETNX and HSETNX.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment