Module: Nagios::Promoo::Utils::Cache

Included in:
Occi::Probes::ComputeProbe
Defined in:
lib/nagios/promoo/utils.rb

Overview

Caching helpers for arbitrary use.

Author:

Constant Summary collapse

CACHE_DIR =
'/tmp/nagios-promoo_cache'.freeze

Instance Method Summary collapse

Instance Method Details

#cache_fetch(key, expiration = 3600) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/nagios/promoo/utils.rb', line 13

def cache_fetch(key, expiration = 3600)
  raise 'You have to provide a block!' unless block_given?
  FileUtils.mkdir_p CACHE_DIR
  filename = File.join(CACHE_DIR, key)

  if cache_valid?(filename, expiration)
    read_cache filename
  else
    write_cache filename, yield
  end
end

#cache_valid?(filename, expiration) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
48
49
# File 'lib/nagios/promoo/utils.rb', line 45

def cache_valid?(filename, expiration)
  File.exist?(filename) \
    && !File.zero?(filename) \
    && ((Time.now - expiration) < File.stat(filename).mtime)
end

#read_cache(filename) ⇒ Object



25
26
27
28
29
30
# File 'lib/nagios/promoo/utils.rb', line 25

def read_cache(filename)
  File.open(filename, 'r') do |file|
    file.flock(File::LOCK_SH)
    JSON.parse file.read
  end
end

#write_cache(filename, data) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/nagios/promoo/utils.rb', line 32

def write_cache(filename, data)
  return data if data.blank?

  File.open(filename, File::RDWR | File::CREAT, 0o644) do |file|
    file.flock(File::LOCK_EX)
    file.write JSON.fast_generate(data)
    file.flush
    file.truncate(file.pos)
  end

  data
end