Class: Restruct::Cache

Inherits:
Structure show all
Includes:
Enumerable
Defined in:
lib/restruct/cache.rb

Direct Known Subclasses

MarshalCache

Instance Attribute Summary collapse

Attributes inherited from Structure

#connection, #id

Instance Method Summary collapse

Methods inherited from Structure

#==, #exists?

Constructor Details

#initialize(options = {}) ⇒ Cache

Returns a new instance of Cache.



8
9
10
11
# File 'lib/restruct/cache.rb', line 8

def initialize(options={})
  super options
  @ttl = options[:ttl]
end

Instance Attribute Details

#ttlObject (readonly)

Returns the value of attribute ttl.



6
7
8
# File 'lib/restruct/cache.rb', line 6

def ttl
  @ttl
end

Instance Method Details

#[](key) ⇒ Object



25
26
27
# File 'lib/restruct/cache.rb', line 25

def [](key)
  deserialize connection.call('GET', id[key])
end

#[]=(key, value) ⇒ Object



29
30
31
32
# File 'lib/restruct/cache.rb', line 29

def []=(key, value)
  connection.lazy 'SET', id[key], serialize(value)
  connection.lazy 'EXPIRE', id[key], ttl if ttl
end

#delete(key) ⇒ Object



34
35
36
37
38
# File 'lib/restruct/cache.rb', line 34

def delete(key)
  value = self[key]
  connection.lazy 'DEL', id[key]
  value
end

#destroyObject Also known as: clear



77
78
79
80
# File 'lib/restruct/cache.rb', line 77

def destroy
  keys.each { |k| connection.lazy 'DEL', id[k] }
  self
end

#eachObject



51
52
53
# File 'lib/restruct/cache.rb', line 51

def each
  keys.each { |key| yield key, self[key] }
end

#empty?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/restruct/cache.rb', line 61

def empty?
  size == 0
end

#fetch(key, &block) ⇒ Object



40
41
42
43
44
45
46
47
48
49
# File 'lib/restruct/cache.rb', line 40

def fetch(key, &block)
  if key? key
    connection.lazy 'EXPIRE', id[key], ttl if ttl
    self[key]
  else
    value = block.call
    self[key] = value
    value
  end
end

#key?(key) ⇒ Boolean Also known as: has_key?

Returns:

  • (Boolean)


13
14
15
# File 'lib/restruct/cache.rb', line 13

def key?(key)
  connection.call('EXISTS', id[key]) == 1
end

#keysObject



18
19
20
21
22
23
# File 'lib/restruct/cache.rb', line 18

def keys
  sections = id.sections.count + 1
  connection.call('KEYS', id['*']).map do |k| 
    Id.new(k).sections.take(sections).last
  end.uniq.sort
end

#restore(dump) ⇒ Object



73
74
75
# File 'lib/restruct/cache.rb', line 73

def restore(dump)
  dump.each { |k,v| self[k] = v }
end

#sizeObject Also known as: count, length



55
56
57
# File 'lib/restruct/cache.rb', line 55

def size
  keys.count
end

#to_hObject Also known as: to_primitive, dump



65
66
67
68
69
# File 'lib/restruct/cache.rb', line 65

def to_h
  keys.each_with_object({}) do |key, hash|
    hash[key] = self[key]
  end
end