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) ⇒ UberCache

Returns a new instance of UberCache.



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

def initialize(cache_prefix, hosts)
  @cache_prefix = cache_prefix
  @hosts = hosts
end

Instance Method Details

#clear(key) ⇒ Object



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

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

#clear_allObject



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

def clear_all
  client.flush
end

#obj_clear(master_key) ⇒ Object



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

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

#obj_read(master_key) ⇒ Object

UberObjectCache



46
47
48
49
50
51
52
53
54
55
# File 'lib/uber_cache.rb', line 46

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



74
75
76
77
78
79
80
81
82
# File 'lib/uber_cache.rb', line 74

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



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/uber_cache.rb', line 57

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



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

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

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



27
28
29
30
31
32
33
34
35
# File 'lib/uber_cache.rb', line 27

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.



21
22
23
24
25
# File 'lib/uber_cache.rb', line 21

def write(key, value = nil, opts = {}, &blk)
  value = blk.call() if blk
  ttl = opts[:ttl]
  client.set(keyify(key), value, ttl)
end