Class: Terjira::FileCache

Inherits:
Object
  • Object
show all
Defined in:
lib/terjira/utils/file_cache.rb

Constant Summary collapse

MAX_DEPTH =
32
ROOT_DIR =
ENV['HOME'] ? "#{ENV['HOME']}/.terjira/" : '~/.terjira/'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(domain, expiry = 0, depth = 2) ⇒ FileCache

Returns a new instance of FileCache.



17
18
19
20
21
22
# File 'lib/terjira/utils/file_cache.rb', line 17

def initialize(domain, expiry = 0, depth = 2)
  @domain  = domain
  @expiry  = expiry
  @depth   = depth > MAX_DEPTH ? MAX_DEPTH : depth
  FileUtils.mkdir_p(root_path)
end

Class Method Details

.clear_allObject



10
11
12
13
14
# File 'lib/terjira/utils/file_cache.rb', line 10

def clear_all
  return unless File.exist?(ROOT_DIR)
  FileUtils.rm_r(ROOT_DIR)
  FileUtils.mkdir_p(ROOT_DIR)
end

Instance Method Details

#clearObject

Delete ALL data from the cache, regardless of expiry time



67
68
69
70
71
# File 'lib/terjira/utils/file_cache.rb', line 67

def clear
  return unless File.exist?(root_path)
  FileUtils.rm_r(root_path)
  FileUtils.mkdir_p(root_path)
end

#delete(key) ⇒ Object

Delete the value for the given key from the cache



62
63
64
# File 'lib/terjira/utils/file_cache.rb', line 62

def delete(key)
  FileUtils.rm(get_path(key)) if File.exists? get_path(key)
end

#fetch(key) ⇒ Object

Return the value for the specified key from the cache if the key exists in the cache, otherwise set the value returned by the block. Returns the value if found or the value from calling the block that was set.



53
54
55
56
57
58
59
# File 'lib/terjira/utils/file_cache.rb', line 53

def fetch(key)
  value = get(key)
  return value if value
  value = yield
  set(key, value)
  value
end

#get(key) ⇒ Object

Return the value for the specified key from the cache. Returns nil if the value isn’t found.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/terjira/utils/file_cache.rb', line 35

def get(key)
  path = get_path(key)

  if @expiry > 0 && File.exist?(path) && Time.new - File.new(path).mtime >= @expiry
    FileUtils.rm(path)
  end

  return nil unless File.exist?(path)
  result = nil
  File.open(path, 'r') do |f|
    result = Marshal.load(f)
  end
  result
end

#purgeObject

Delete all expired data from the cache



74
75
76
77
# File 'lib/terjira/utils/file_cache.rb', line 74

def purge
  @t_purge = Time.new
  purge_dir(root_path) if @expiry > 0
end

#set(key, value) ⇒ Object

Set a cache value for the given key. If the cache contains an existing value for the key it will be overwritten.



26
27
28
29
30
31
# File 'lib/terjira/utils/file_cache.rb', line 26

def set(key, value)
  f = File.open(get_path(key), 'w')
  File.chmod(0600, f) unless File.stat(f).mode.to_s(8) =~ /600/
  Marshal.dump(value, f)
  f.close
end