Sha256: 4adb168e0a2386145ec9008a67050c4c06e4ef634195af68e64815eb8bfd4ecd

Contents?: true

Size: 609 Bytes

Versions: 9

Compression:

Stored size: 609 Bytes

Contents

module Datacenter
  class Cache

    def initialize(expiration_time=nil)
      @expiration_time = expiration_time
      @data = {}
    end

    def fetch(key, &block)
      set key, block.call if !data.key?(key) || expired?(key)
      get key
    end

    private

    attr_reader :data, :expiration_time

    def get(key)
      data[key][:value]
    end

    def set(key, value)
      data[key] = {
        value: value,
        fetched_at: Time.now
      }
    end

    def expired?(key)
      return false unless expiration_time
      Time.now >= data[key][:fetched_at] + expiration_time
    end

  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
datacenter-0.5.1 lib/datacenter/cache.rb
datacenter-0.5.0 lib/datacenter/cache.rb
datacenter-0.4.4 lib/datacenter/cache.rb
datacenter-0.4.3 lib/datacenter/cache.rb
datacenter-0.4.2 lib/datacenter/cache.rb
datacenter-0.4.0 lib/datacenter/cache.rb
datacenter-0.3.1 lib/datacenter/cache.rb
datacenter-0.2.2 lib/datacenter/cache.rb
datacenter-0.2.1 lib/datacenter/cache.rb