Sha256: 01122f93efa1a5bf38f41eddb354f8ecc6cc24d7b1f62de0bc952220f001c6bc

Contents?: true

Size: 984 Bytes

Versions: 1

Compression:

Stored size: 984 Bytes

Contents

module Ncn
  class Cache
    attr_reader :path

    def initialize(path)
      @path = path
    end

    def fetch(key, value = nil)
      return get(key) if exist?(key)
      (value || (block_given? ? yield : nil))&.tap { set(key, _1) }
    end

    def exist?(key)
      cache.key?(key.to_s)
    end

    # Add key with associated value to the cache
    # @param [String] cache key
    # @param [String] value to associate with the key
    # @return [Object] original value
    def set(key, value)
      cache[key.to_s] = value
      persist
      value
    end

    def get(key)
      cache[key.to_s]
    end

    def unset(key)
      return unless exist?(key)
      cache.delete(key.to_s)
      persist
    end

    def keys
      cache.keys
    end

    private

    def persist
      FileUtils.mkdir_p(File.dirname(path))
      File.write(path, JSON.generate(cache))
    end

    def cache
      @cache ||= File.exist?(path) ? JSON.parse(File.read(path)) : {}
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ncn-0.1.0 lib/ncn/cache.rb