class UberCache

Constants

OBJ_MAX_SIZE

Public Class Methods

new(cache_prefix, hosts, opts = {}) click to toggle source
# File lib/uber_cache.rb, line 10
def initialize(cache_prefix, hosts, opts = {})
  @cache_prefix = cache_prefix
  @dalli_opts = opts
  @hosts = hosts
end

Public Instance Methods

clear(key) click to toggle source
# File lib/uber_cache.rb, line 38
def clear(key)
  client.set(keyify(key), nil)
end
clear_all() click to toggle source
# File lib/uber_cache.rb, line 42
def clear_all
  client.flush
end
obj_clear(master_key) click to toggle source
# File lib/uber_cache.rb, line 71
def obj_clear(master_key)
  clear("#{master_key}-0")
end
obj_read(master_key) click to toggle source

UberObjectCache

# File lib/uber_cache.rb, line 47
def obj_read(master_key)
  data = []
  segment = 0
  while(more_data = read("#{master_key}-#{segment}"))
    data << more_data
    segment += 1
  end
  return nil if data.length == 0
  return Marshal::load(data.join(""))
end
obj_read_or_write(master_key, opts = {}, &blk) click to toggle source
# File lib/uber_cache.rb, line 75
def obj_read_or_write(master_key, opts = {}, &blk)
  found = obj_read(master_key)
  reload = opts.delete(:reload) || false
  return found if found && !reload
  value = nil
  value = blk.call() if blk
  obj_write(master_key, value, opts)
  return value
end
obj_write(master_key, obj = nil, opts = {}, &blk) click to toggle source
# File lib/uber_cache.rb, line 58
def obj_write(master_key, obj = nil, opts = {}, &blk)
  obj = blk.call() if blk
  max_size = opts.delete(:max_size) || OBJ_MAX_SIZE
  data = Marshal::dump(obj)
  segment = 0
  while(data)
    write("#{master_key}-#{segment}", data.slice(0, max_size), opts)
    data = data.slice(max_size, data.length)
    segment += 1
  end
  clear("#{master_key}-#{segment}")
end
read(key) click to toggle source

read from the cache

# File lib/uber_cache.rb, line 17
def read(key)
  client.get(keyify(key))
end
read_or_write(key, opts = {}, &blk) click to toggle source
# File lib/uber_cache.rb, line 28
def read_or_write(key, opts = {}, &blk)
  found = client.get(keyify(key))
  return found unless found.nil?
  value = nil
  value = blk.call() if blk
  ttl = opts[:ttl]
  client.set(keyify(key), value, ttl)
  return value
end
write(key, value = nil, opts = {}, &blk) click to toggle source

write to the cache - value will pull from passed block if block is passed.

# File lib/uber_cache.rb, line 22
def write(key, value = nil, opts = {}, &blk)
  value = blk.call() if blk
  ttl = opts[:ttl]
  client.set(keyify(key), value, ttl)
end

Private Instance Methods

client() click to toggle source
# File lib/uber_cache.rb, line 86
def client
  @client ||= Dalli::Client.new(@hosts, @dalli_opts)
end
keyify(key) click to toggle source

namespace the keys - to not kill other stuff.

# File lib/uber_cache.rb, line 91
def keyify(key)
  "#{@cache_prefix}:#{key}"
end