Class: Milkshake::Cache

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Cache

Returns a new instance of Cache.



7
8
9
10
11
12
13
14
15
16
# File 'lib/milkshake/cache.rb', line 7

def initialize(path)
  @path = path
  begin
    File.open(@path, 'r') { |f| @entries = Marshal.load(f.read) }
    raise 'wrong type' unless Hash === @entries
  rescue
    @entries = {}
  end
  @history = []
end

Instance Attribute Details

#entriesObject

Returns the value of attribute entries.



5
6
7
# File 'lib/milkshake/cache.rb', line 5

def entries
  @entries
end

#historyObject

Returns the value of attribute history.



5
6
7
# File 'lib/milkshake/cache.rb', line 5

def history
  @history
end

#pathObject

Returns the value of attribute path.



5
6
7
# File 'lib/milkshake/cache.rb', line 5

def path
  @path
end

Instance Method Details

#[](name) ⇒ Object



28
29
30
# File 'lib/milkshake/cache.rb', line 28

def [](name)
  @entries[name.to_s]
end

#[]=(name, value) ⇒ Object



32
33
34
# File 'lib/milkshake/cache.rb', line 32

def []=(name, value)
  @entries[name.to_s] = value
end

#key(name) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/milkshake/cache.rb', line 18

def key(name)
  if @entries.key?(name.to_s)
    @entries[name.to_s]
  elsif block_given?
    @entries[name.to_s] = yield
  else
    nil
  end
end

#persist!Object



45
46
47
# File 'lib/milkshake/cache.rb', line 45

def persist!
  File.open(@path, 'w+') { |f| f.write Marshal.dump(@entries) }
end

#reset!Object



36
37
38
39
# File 'lib/milkshake/cache.rb', line 36

def reset!
  @history << @entries
  @entries = {}
end

#restore!Object



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

def restore!
  @entries = @history.pop || {}
end