Class: FileCache

Inherits:
Cache show all
Defined in:
lib/libcache/file_cache.rb

Instance Attribute Summary

Attributes inherited from Cache

#expiry_time, #max_size, #refresh, #store

Instance Method Summary collapse

Methods inherited from Cache

#check_refresh, #exists?, #get_size, #has_refresh?

Constructor Details

#initializeFileCache

Returns a new instance of FileCache.



7
8
9
# File 'lib/libcache/file_cache.rb', line 7

def initialize
  super
end

Instance Method Details

#create_storeObject

Initializes the cache store along with the keys store. Raises an exception if the store path is not supplied.



12
13
14
15
16
17
18
# File 'lib/libcache/file_cache.rb', line 12

def create_store
  @cache = Hash.new
  @keys = Hash.new
  if store == nil
    raise 'Store path is missing!'
  end
end

#get(key) ⇒ Object

Gets the object that corresponds with the key that is read from the filesystem

Parameters:

  • key (String)

    The key value used to identify an object in the cache

Returns:

  • (Object)

    The object that corresponds with the key



47
48
49
50
# File 'lib/libcache/file_cache.rb', line 47

def get(key)
  refresh
  return File.read(File.join(store, @keys[key]))
end

#invalidate(key) ⇒ Object

Deletes a key-value pair from the cache and store directory

Parameters:

  • key (String)

    The key value used to identify an object in the cache



54
55
56
57
58
# File 'lib/libcache/file_cache.rb', line 54

def invalidate(key)
  super
  @keys.delete key
  File.delete(File.join(store, @keys[key]))
end

#invalidateAllObject

Clears all items in the cache and the cached files in the store directory



61
62
63
64
65
66
# File 'lib/libcache/file_cache.rb', line 61

def invalidateAll
  super
  Dir.foreach(store) do |f|
    File.delete(File.join(store, f)) if f != '.' && f != '..'
  end
end

#put(key, value) ⇒ Object

Places an object inside the cache, and by extension, into the filesystem. Handles max size eviction. Raises an InvalidKey exception if the key is not formatted properly.

Parameters:

  • key (String)

    The key value used to identify an object in the cache

  • value (Object)

    The object to be placed in the cache

Raises:

  • (InvalidKey)


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/libcache/file_cache.rb', line 23

def put(key, value)
  raise InvalidKey unless key.is_a? String
  raise InvalidKey unless key =~ /\A[a-zA-Z0-9_-]+\z/
  if max_size != nil
    if @cache.size >= max_size - 1
      key, value = @time_tracker.values.sort {|v| Time.now - v }.reverse.first
      invalidate(key)
      @time_tracker.delete(key)
    end
    @time_tracker[key] = Time.now
  end
  @keys[key] = Digest::MD5.hexdigest(key) + Time.now.to_i.to_s
  @cache[key] = value
  File.open(File.join(store, @keys[key]), 'w') do |f|
    f.write(value)
  end
  @scheduler.in expiry_time, :blocking => true do
    invalidate key
  end
end