Sha256: f28df2094c1830c6ba70b6e210601391797f5113924f1725c677d3bb5ec0b6f9

Contents?: true

Size: 618 Bytes

Versions: 4

Compression:

Stored size: 618 Bytes

Contents

module Datacenter
  class Cache

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

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

    private

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

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

    def key?(key)
      @data.key? key
    end

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

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
datacenter-0.2.0 lib/datacenter/cache.rb
datacenter-0.1.2 lib/datacenter/cache.rb
datacenter-0.1.1 lib/datacenter/cache.rb
datacenter-0.1.0 lib/datacenter/cache.rb