Sha256: cf9a06f1947fd967a40936b8ac4bc478a1f905897f795e3fa4f58da6f335bd75

Contents?: true

Size: 810 Bytes

Versions: 26

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

26 entries across 26 versions & 1 rubygems

Version Path
mux_tf-0.8.3 lib/mux_tf/yaml_cache.rb
mux_tf-0.8.2 lib/mux_tf/yaml_cache.rb
mux_tf-0.8.1 lib/mux_tf/yaml_cache.rb
mux_tf-0.8.0 lib/mux_tf/yaml_cache.rb
mux_tf-0.7.2 lib/mux_tf/yaml_cache.rb
mux_tf-0.7.1 lib/mux_tf/yaml_cache.rb
mux_tf-0.7.0 lib/mux_tf/yaml_cache.rb
mux_tf-0.6.1 lib/mux_tf/yaml_cache.rb
mux_tf-0.6.0 lib/mux_tf/yaml_cache.rb
mux_tf-0.5.3 lib/mux_tf/yaml_cache.rb
mux_tf-0.5.2 lib/mux_tf/yaml_cache.rb
mux_tf-0.5.1 lib/mux_tf/yaml_cache.rb
mux_tf-0.5.0 lib/mux_tf/yaml_cache.rb
mux_tf-0.4.9 lib/mux_tf/yaml_cache.rb
mux_tf-0.4.8 lib/mux_tf/yaml_cache.rb
mux_tf-0.4.7 lib/mux_tf/yaml_cache.rb
mux_tf-0.4.6 lib/mux_tf/yaml_cache.rb
mux_tf-0.4.5 lib/mux_tf/yaml_cache.rb
mux_tf-0.4.4 lib/mux_tf/yaml_cache.rb
mux_tf-0.4.3 lib/mux_tf/yaml_cache.rb