Class: VirtualFS::FileCache

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ FileCache

Returns a new instance of FileCache.



7
8
9
10
11
# File 'lib/virtualfs/file_cache.rb', line 7

def initialize(opts={})
  @expires_after = opts[:expires_after] || -1

  @store = PStore.new(opts[:filename] || 'virtualfs.pstore')
end

Instance Attribute Details

#expires_afterObject

Returns the value of attribute expires_after.



5
6
7
# File 'lib/virtualfs/file_cache.rb', line 5

def expires_after
  @expires_after
end

Instance Method Details

#cache(key, &proc) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/virtualfs/file_cache.rb', line 13

def cache(key, &proc)
  access_time = Time.now

  @store.transaction do
    data = @store[key] || {:time => access_time, :content => nil}

    # Invalidate cache after some time
    if (@expires_after > -1) && ((access_time - data[:time]) > @expires_after)
      data = {:time => access_time, :content => nil}
    end

    data[:content] ||= yield
    @store[key] = data

    data[:content]
  end
end