Sha256: 178363bdcf890e5f998c42f082b1da22d365ba7951f931e6b1cef8186915f607

Contents?: true

Size: 810 Bytes

Versions: 5

Compression:

Stored size: 810 Bytes

Contents

require 'yaml/store'

module MuxTf
  class YamlCache
    def initialize(path, default_ttl:)
      @default_ttl = default_ttl
      @store = YAML::Store.new path
    end

    def set(key, value, ttl: @default_ttl)
      @store.transaction do
        @store[key] = {
          expires_at: Time.now + ttl,
          value: value
        }
      end
    end

    def fetch(key, ttl: @default_ttl)
      info = nil
      @store.transaction(true) do
        info = @store[key]
      end

      if info.nil? || info[:expires_at] < Time.now
        if block_given?
          value = yield
          set(key, value, ttl: ttl)
          return value
        else
          raise KeyError, info.nil? ? "no value at key: #{key}" : "value expired at key: #{key}"
        end
      end

      info[:value]
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
mux_tf-0.2.4 lib/mux_tf/yaml_cache.rb
mux_tf-0.2.3 lib/mux_tf/yaml_cache.rb
mux_tf-0.2.2 lib/mux_tf/yaml_cache.rb
mux_tf-0.2.1 lib/mux_tf/yaml_cache.rb
mux_tf-0.2.0 lib/mux_tf/yaml_cache.rb