Class: Jsus::Util::FileCache

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

Overview

Simple file cache manager.

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ FileCache

Initializes filecache to given directory

Parameters:

  • output (String)

    directory



11
12
13
# File 'lib/jsus/util/file_cache.rb', line 11

def initialize(path)
  @path = path
end

Instance Method Details

#delete(key) ⇒ Object

Deletes cache entry for given key.

Parameters:

  • key (String)


48
49
50
51
52
53
# File 'lib/jsus/util/file_cache.rb', line 48

def delete(key)
  item_path = generate_path(key)
  if File.exists?(item_path)
    FileUtils.rm_f(item_path)
  end
end

#fetch(key) { ... } ⇒ String

Returns path to stored file.

Parameters:

  • key (String)

Yields:

  • block with routine to call on cache miss

Returns:

  • (String)

    path to stored file



41
42
43
# File 'lib/jsus/util/file_cache.rb', line 41

def fetch(key, &block)
  read(key) || write(key, yield)
end

#read(key) ⇒ String? Also known as: exists?

Returns path to cached file or nil.

Parameters:

  • key (String)

Returns:

  • (String, nil)

    path to cached file or nil



31
32
33
34
# File 'lib/jsus/util/file_cache.rb', line 31

def read(key)
  item_path = generate_path(key)
  File.exists?(item_path) ? item_path : nil
end

#write(key, value) ⇒ String

Creates a file with given value for given key in cache directory

Parameters:

  • key (String)
  • value (String)

Returns:

  • (String)

    actual path for stored file.



21
22
23
24
25
26
# File 'lib/jsus/util/file_cache.rb', line 21

def write(key, value)
  item_path = generate_path(key)
  FileUtils.mkdir_p(File.dirname(item_path))
  File.open(item_path, 'w+') {|f| f.write(value) }
  item_path
end