Class: UberCache

Inherits:
Object
  • Object
show all
Defined in:
lib/uber_cache.rb

Constant Summary collapse

OBJ_MAX_SIZE =
1000000

Instance Method Summary collapse

Constructor Details

#initialize(cache_prefix, hosts, opts = {}) ⇒ UberCache

Returns a new instance of UberCache.



10
11
12
13
14
# File 'lib/uber_cache.rb', line 10

def initialize(cache_prefix, hosts, opts = {})
  @cache_prefix = cache_prefix
  @dalli_opts = opts
  @hosts = hosts
end

Instance Method Details

#clear(key) ⇒ Object



38
39
40
# File 'lib/uber_cache.rb', line 38

def clear(key)
  client.set(keyify(key), nil)
end

#clear_allObject



42
43
44
# File 'lib/uber_cache.rb', line 42

def clear_all
  client.flush
end

#obj_clear(master_key) ⇒ Object



71
72
73
# File 'lib/uber_cache.rb', line 71

def obj_clear(master_key)
  clear("#{master_key}-0")
end

#obj_read(master_key) ⇒ Object

UberObjectCache



47
48
49
50
51
52
53
54
55
56
# 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) ⇒ Object



75
76
77
78
79
80
81
82
83
# 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) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
# 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) ⇒ Object

read from the cache



17
18
19
# File 'lib/uber_cache.rb', line 17

def read(key)
  client.get(keyify(key))
end

#read_or_write(key, opts = {}, &blk) ⇒ Object



28
29
30
31
32
33
34
35
36
# 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) ⇒ Object

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



22
23
24
25
26
# 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