Class: MuxTf::YamlCache

Inherits:
Object
  • Object
show all
Defined in:
lib/mux_tf/yaml_cache.rb

Instance Method Summary collapse

Constructor Details

#initialize(path, default_ttl:) ⇒ YamlCache

Returns a new instance of YamlCache.



43
44
45
46
# File 'lib/mux_tf/yaml_cache.rb', line 43

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

Instance Method Details

#fetch(key, ttl: @default_ttl) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mux_tf/yaml_cache.rb', line 57

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

  if info.nil? || info[:expires_at] < Time.now
    raise KeyError, info.nil? ? "no value at key: #{key}" : "value expired at key: #{key}" unless block_given?

    value = yield
    set(key, value, ttl: ttl)
    return value

  end

  info[:value]
end

#set(key, value, ttl: @default_ttl) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/mux_tf/yaml_cache.rb', line 48

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