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') { |file| @entries = Marshal.load(file.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



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

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

#[]=(name, value) ⇒ Object



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

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

#key(name) ⇒ Object



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

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

#persist!Object



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

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

#reset!Object



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

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

#restore!Object



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

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