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



60
61
62
63
# File 'lib/mux_tf/yaml_cache.rb', line 60

def initialize(path, default_ttl:)
  @default_ttl = default_ttl
  @store = UnsafeYamlStore.new path, { aliases: true, permitted_classes: [Symbol, Time] }
end

Instance Method Details

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



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/mux_tf/yaml_cache.rb', line 74

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



65
66
67
68
69
70
71
72
# File 'lib/mux_tf/yaml_cache.rb', line 65

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