Skip to content

Instantly share code, notes, and snippets.

@asqd
Created February 29, 2016 14:43
Show Gist options
  • Save asqd/85ab860552fe4d6ae055 to your computer and use it in GitHub Desktop.
Save asqd/85ab860552fe4d6ae055 to your computer and use it in GitHub Desktop.
Redis helper mixin for rails
module RedisHelper
REDIS = Redis.current
def self.fetch(key, options={}, &block)
val = get_val(key, options) if REDIS.exists(key)
unless val && block_given?
val = yield
set_val(key, val, options)
end
val
end
def self.find(key, options={})
get_val(key, options)
end
def self.set(key, value, options={})
set_val(key, value, options)
end
private
def self.get_val(key, options)
if options[:marshal]
begin
Marshal.load(REDIS.get(key))
rescue TypeError
nil
end
else
REDIS.get(key)
end
end
def self.set_val(key, val, options)
if options[:marshal]
REDIS.set(key, Marshal.dump(val))
else
REDIS.set(key, val)
end
REDIS.expire key, options[:expiration] if options[:expiration]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment