Class: DiskStash::Cache

Inherits:
Object show all
Includes:
Enumerable
Defined in:
lib/hoodie/stash/disk_store.rb

Overview

Disk stashing method variable caching hash, string, array store.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(store = file_store) ⇒ Object

Initializes a new disked backed stash hash cache store.

Parameters:

  • path (String)

    location for stash store cache.



37
38
39
40
# File 'lib/hoodie/stash/disk_store.rb', line 37

def initialize(store = file_store)
  @store = store
  _ensure_store_directory
end

Instance Attribute Details

#storeString (readonly)

Returns location of DiskStash::Cache.store.

Returns:

  • (String)

    location of DiskStash::Cache.store



29
30
31
# File 'lib/hoodie/stash/disk_store.rb', line 29

def store
  @store
end

Instance Method Details

#[](key) ⇒ Hash, ...

Retrieves the value for a given key, if nothing is set, returns nil

Parameters:

  • key (Symbol, String)

    representing the key

Returns:



67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/hoodie/stash/disk_store.rb', line 67

def [](key)
  if key.is_a? Array
    hash = {}
    key.each do |k|
      hash[k] = Marshal.load(_read_cache_file(k))
    end
    hash unless hash.empty?
  else
    Marshal.load(_read_cache_file(key))
  end
rescue Errno::ENOENT
  nil # key hasn't been created
end

#[]=(key, value) ⇒ Object

Store the given value with the given key, either an an argument or block. If a previous value was set it will be overwritten with the new value.

Parameters:

  • key (Symbol, String)

    representing the key

  • value (Object)

    that represents the value (optional)

  • block (&block)

    that returns the value to set (optional)

Returns:

  • nothing.



91
92
93
# File 'lib/hoodie/stash/disk_store.rb', line 91

def []=(key, value)
  _write_cache_file(key, Marshal.dump(value))
end

#cache_file(key) ⇒ Object

returns path to cache file with ‘key’



96
97
98
# File 'lib/hoodie/stash/disk_store.rb', line 96

def cache_file(key)
  ::File.join(store, key.to_s + '.cache')
end

#clear!(key = nil) ⇒ Hash

Clear the whole stash or the value of a key

representing the key to clear

returns {}

Parameters:

  • key (Symbol, String) (defaults to: nil)

    (optional) string or symbol

Returns:

  • (Hash)

    with a key, return the value it had, without



50
51
52
53
54
55
56
57
58
# File 'lib/hoodie/stash/disk_store.rb', line 50

def clear!(key = nil)
  if key.nil?
    ::Dir[::File.join(store, '*.cache')].each do |file|
      ::File.delete(file)
    end
  else
    ::File.delete(cache_file(key)) if ::File.exist?(cache_file(key))
  end
end