Skip to content

Instantly share code, notes, and snippets.

@oleganza
Created July 9, 2009 12:23
Show Gist options
  • Save oleganza/143615 to your computer and use it in GitHub Desktop.
Save oleganza/143615 to your computer and use it in GitHub Desktop.
# Simple cache implementation for DB supporting simple collection retrieval
# Static types (i.e. tables) are omitted for brevity.
class Repository
attr_accessor :object_cache, :collection_cache, :backend
def get(id)
get_many([id]).first
end
def get_many(ids)
cached_objs = object_cache.get(ids)
missed_ids = ids - objs.map{|o| o.id}
missed_objects = backend.get(missed_ids)
object_cache.put(missed_objects)
cached_objs + missed_objects
end
# id = "123", properties = {"name" => "Oleg", "age" => 22}
def put(id, old_properties, new_properties)
object_cache.delete([id])
collection_cache.delete(old_properties)
collection_cache.delete(new_properties)
backend.put(id, new_properties)
end
# album.photos == repository.get_collection("album_id", album.id)
def get_collection(property_name, value)
cached_ids = collection_cache.get(property_name, value)
ids = if cached_ids
cached_ids
else
ids = backend.get_collection(property_name, value)
collection_cache.put(property_name, value, ids)
ids
end
get_many(ids)
end
class ObjectCache
def get(ids)
ids.map{|id| @hash[id] }
end
def put(objs)
objs.map{|obj| @hash[obj.id] = obj }
self
end
def delete(ids)
ids.each{|id| @hash.delete(id) }
self
end
end
class CollectionCache
def get(property_name, value)
@hash[key(property_name,value)]
end
def put(property_name, value, ids)
@hash[key(property_name,value)] = ids
self
end
def delete(properties) # {key => value}
properties.each{|n, v| @hash.delete(key(n,v)) }
self
end
def key(name, value)
"#{name}:#{value}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment