Class: Drydock::ObjectCaches::FilesystemCache

Inherits:
Base
  • Object
show all
Defined in:
lib/drydock/object_caches/filesystem_cache.rb

Instance Method Summary collapse

Constructor Details

#initialize(dir = "~/.drydock") ⇒ FilesystemCache

Returns a new instance of FilesystemCache.



8
9
10
11
# File 'lib/drydock/object_caches/filesystem_cache.rb', line 8

def initialize(dir = "~/.drydock")
  @dir = File.expand_path(File.join(dir.to_s, 'cache'))
  FileUtils.mkdir_p(@dir)
end

Instance Method Details

#clearObject



13
14
15
16
17
18
19
20
21
# File 'lib/drydock/object_caches/filesystem_cache.rb', line 13

def clear
  begin
    FileUtils.remove_entry(@dir)
    true
  rescue => e
    Drydock.logger.error("Cannot clear #{self.class} at #{@dir.inspect}: #{e}")
    return false
  end
end

#fetch(key, &blk) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/drydock/object_caches/filesystem_cache.rb', line 23

def fetch(key, &blk)
  filename = build_path(key)

  if File.exist?(filename)
    File.read(filename)
  else
    dirname = File.dirname(filename)
    FileUtils.mkdir_p(dirname)

    blk.call.tap do |contents|
      File.open(filename, 'w') do |file|
        file.write contents
      end
    end
  end
end

#get(key, &blk) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/drydock/object_caches/filesystem_cache.rb', line 40

def get(key, &blk)
  filename = build_path(key)
  if File.exist?(filename)
    if blk.nil?
      File.read(filename)
    else
      File.open(filename) do |file|
        blk.call file
      end
    end
  else
    nil
  end
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/drydock/object_caches/filesystem_cache.rb', line 55

def key?(key)
  File.exist?(build_path(key))
end

#set(key, value = nil, &blk) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/drydock/object_caches/filesystem_cache.rb', line 59

def set(key, value = nil, &blk)
  filename = build_path(key)
  dirname = File.dirname(filename)
  FileUtils.mkdir_p(dirname)

  File.open(filename, 'w') do |file|
    if blk.nil?
      file.write value
    else
      blk.call file
    end
  end

  nil
end