Skip to content

Instantly share code, notes, and snippets.

@mfojtik
Created April 26, 2012 15:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfojtik/2500548 to your computer and use it in GitHub Desktop.
Save mfojtik/2500548 to your computer and use it in GitHub Desktop.
memcached sample
require 'dalli'
require 'redis'
require 'pp'
module Cache
def self.[](*keys)
if keys.size == 1
value = self.get(keys.first)
value.extend(CacheMethods) && value.__key__(keys.first)
value
else
values = self.get_multiple(keys)
values.inject({}) { |r,(k,v)| v.extend(CacheMethods) && v.__key__(k) ; r[k]=v; r }
end
end
def self.<<(data)
data.each { |k, v| self[k]=v }
end
def self.[]=(key, value)
self.set(key, value)
end
def self.delete(key)
cache { |m| m.delete(key) }
end
module CacheMethods
def method_missing(name, *args)
case name
when :'__key__' then @__key__=args.first
when :expire then Cache.delete(@__key__)
when :'save!' then Cache.make_persistent(@__key__)
else super
end
end
end
def self.load!
persistence_client.hgetall(:cache).each { |k,v| self[k] = v }
end
private
def self.get_multiple(*keys)
cache do |m|
m.get_multi(keys)
end
end
def self.get(key)
cache do |m|
m.get(key)
end
end
def self.set(key, value)
cache do |m|
m.set(key, value)
end
end
def self.make_persistent(key)
persistence_client.hset(:cache, key, get(key))
end
def self.cache(servers=nil, options={})
if block_given?
result = yield c = client(servers, options)
c.close
result
else
client(servers, options)
end
end
def self.client(servers=nil, options={})
Dalli::Client.new(servers || ["localhost:11211"], options)
end
def self.persistence_client(options={})
Redis.connect(options)
end
end
# Show-case:
pp Cache[:bible] = '4.1' # Store the value to key
pp Cache[:bible] # Read the value
pp Cache[:bible].expire # Expire key
pp Cache[:bible] # Should print nil
pp Cache << { :adidas => '3.5', :nike => '3.1' } # Store multiple keys
pp Cache[:adidas] # Read the value
pp Cache[:nike] # Read the value
pp Cache[:adidas, :nike] # Should retrieve multiple keys efficiently
# Expire multiple values
Cache[:adidas, :nike].each do |k, v|
v.expire
end
pp Cache[:adidas, :nike] # Should be nil
pp '============================================='
pp Cache[:adidas] = '1.0'
Cache[:adidas].save!
Cache.load!
pp Cache[:adidas]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment