Skip to content

Instantly share code, notes, and snippets.

@edvardm
Created March 6, 2013 08:36
Show Gist options
  • Save edvardm/5097670 to your computer and use it in GitHub Desktop.
Save edvardm/5097670 to your computer and use it in GitHub Desktop.
Simple redis cache helper, always evaluates value if Redis is down
module RedisHelper
def redis
@redis ||= Redis.new.tap do
@redis_available = true
end
end
def ns_key(k)
"enfo_sm:#{k}"
end
def maybe_get(k)
redis.get(k)
rescue Redis::CannotConnectError
warn "Cannot connect to redis instance"
@redis_available = false
nil
end
# call value stored under key, optionally setting expire time in seconds (default 10).
# If not found, block is called and value is cached.
# Object must be serializable with Marshal. Expire is set only when calling the block.
def cache_get(key, opts={}, &block)
k = ns_key(k)
if v = maybe_get(k) # either key is not found, or cannot connect to redis
Marshal::load(v)
else
block.call.tap do |v|
if @redis_available
redis.set(k, Marshal::dump(v))
redis.expire(k, opts.fetch(:expire, 10))
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment