module Nagios::Promoo::Utils::Cache

Caching helpers for arbitrary use.

@author Boris Parak <parak@cesnet.cz>

Constants

CACHE_DIR

Public Instance Methods

cache_fetch(key, expiration = 3600) { || ... } click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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