module YAVDB::Utils::Cache

Constants

CACHE_MAIN_KEY

Public Class Methods

cache_contents(group_key, key, &body) click to toggle source
# File lib/yavdb/utils/cache.rb, line 28
def self.cache_contents(group_key, key, &body)
  get(group_key, key) || put(group_key, key, body.call)
end
cache_path(group_key, key, &body) click to toggle source
# File lib/yavdb/utils/cache.rb, line 32
def self.cache_path(group_key, key, &body)
  key_path = generate_cache_identifier(group_key, key)
  body.call(key_path) unless File.exist?(key_path)
  key_path
end

Private Class Methods

generate_cache_identifier(group_key, key) click to toggle source
# File lib/yavdb/utils/cache.rb, line 53
def generate_cache_identifier(group_key, key)
  group_key = sanitize_key(group_key)
  key       = sanitize_key(key)

  group_path = if group_key
                 File.expand_path(File.join(YAVDB::Constants::DEFAULT_CACHE_PATH, group_key))
               else
                 File.expand_path(File.join(YAVDB::Constants::DEFAULT_CACHE_PATH, CACHE_MAIN_KEY))
               end

  FileUtils.mkdir_p(group_path) unless File.exist?(group_path)

  File.expand_path(File.join(group_path, key))
end
get(group_key, key) click to toggle source
# File lib/yavdb/utils/cache.rb, line 42
def get(group_key, key)
  key_path = generate_cache_identifier(group_key, key)
  File.open(key_path, 'rb') { |file| Marshal.load(file.read) } if File.exist?(key_path)
end
put(group_key, key, value) click to toggle source
# File lib/yavdb/utils/cache.rb, line 47
def put(group_key, key, value)
  key_path = generate_cache_identifier(group_key, key)
  File.open(key_path, 'wb') { |file| file.write(Marshal.dump(value)) }
  value
end
sanitize_key(key) click to toggle source
# File lib/yavdb/utils/cache.rb, line 68
def sanitize_key(key)
  sanitized_key = key
                    .gsub(%r{[^[:alnum:]]}, '-')
                    .gsub(%r{(-)+}, '-')
                    .gsub(%r{^-}, '')
                    .gsub(%r{-$}, '')

  if sanitized_key == '-'
    hex_key = Digest::SHA256.hexdigest(key)

    puts "Could not sanitize key(#{key}) using #{hex_key} instead"

    hex_key
  elsif sanitized_key.empty?
    random_string = SecureRandom.hex

    puts "Could not sanitize key(#{key}) using #{random_string} instead"

    random_string
  else
    sanitized_key
  end
end