Skip to content

Instantly share code, notes, and snippets.

@vierarb
Last active August 29, 2015 14:03
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 vierarb/0e80f83276110aef67ca to your computer and use it in GitHub Desktop.
Save vierarb/0e80f83276110aef67ca to your computer and use it in GitHub Desktop.
Redis Storage
$redis = Redis.new(host: 'localhost', port: 6379, db: 1)
class RedisJSON < RedisStorage
class << self
def fetch(*args)
key = key(args)
content = cache(key)
content.nil? ? store(key, yield) : parse(content)
end
private
def parse(content)
JSON.parse(content)
end
end
end
class RedisObject < RedisStorage
class << self
def fetch(*args)
key = key(args)
content = cache(key)
if content.nil?
content = Marshal.dump(yield)
store(key, content)
yield
else
parse(content)
end
end
private
def parse(content)
Marshal.load(content)
end
end
end
# Usage:
#
# RedisJSON.fetch(*key, &block)
# RedisObject.fetch(*key, &block)
#
# Dummy Example:
# class User < ActiveRecord::Base
# def whoami
# cache_object(:users, uid) do
# self
# end
# end
#
# def cache_object(*key, &block)
# RedisObject.fetch(*key, &block)
# end
# end
#
# > user = User.first
# > user.id
# => 1
# user.whoami
# => #<User id: 1, ... >
# Marshal.load($redis.get("users:1"))
# => #<User id: 1, ... >
class RedisStorage
class << self
def fetch
fail NotImplementedError, "This #{self.class} cannot respond to:"
end
private
def default_expiration
302400
end
def cache(key)
$redis.get(key)
end
def store(key, content)
$redis.set(key, content)
$redis.expire(key, default_expiration)
store_key(key)
content
end
def get_keys(index)
map = get_map(index)
$redis.smembers(map)
end
def store_keys(*keys)
keys.each { |key| store_key(key) }
end
def store_key(key)
index = get_index(key)
map = get_map(index)
$redis.sadd(map, key)
end
def delete_keys(index)
keys = get_keys(index)
map = get_map(index)
keys.each { |key| delete_key(key) }
delete_key(map)
end
def delete_key(key)
$redis.del(key)
end
def key(*args)
args.compact.join(':')
end
def get_map(index)
"#{index}:keys"
end
def get_index(key)
key.split(':').first
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment