Class: FileCache
Instance Attribute Summary
Attributes inherited from Cache
#expiry_time, #max_size, #refresh, #store
Instance Method Summary collapse
-
#create_store ⇒ Object
Initializes the cache store along with the keys store.
-
#get(key) ⇒ Object
Gets the object that corresponds with the key that is read from the filesystem.
-
#initialize ⇒ FileCache
constructor
A new instance of FileCache.
-
#invalidate(key) ⇒ Object
Deletes a key-value pair from the cache and store directory.
-
#invalidateAll ⇒ Object
Clears all items in the cache and the cached files in the store directory.
-
#put(key, value) ⇒ Object
Places an object inside the cache, and by extension, into the filesystem.
Methods inherited from Cache
#check_refresh, #exists?, #get_size, #has_refresh?
Constructor Details
#initialize ⇒ FileCache
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_store ⇒ Object
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
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
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 |
#invalidateAll ⇒ Object
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.
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 |