Sha256: a8dc7170ecafcfe9b1dfca05de4ac1559a8243d7104528a601d03e95597093b2

Contents?: true

Size: 984 Bytes

Versions: 4

Compression:

Stored size: 984 Bytes

Contents

module Rack
  class Component
    # A threadsafe, in-memory, per-component cache
    class MemoryCache
      attr_reader :store, :mutex

      # Use a hash to store cached calls and a mutex to make it threadsafe
      def initialize(length: 100)
        @store = {}
        @length = length
        @mutex = Mutex.new
      end

      # Fetch a key from the cache, if it exists
      # If the key doesn't exist and a block is passed, set the key
      # @return the cached value
      def fetch(key)
        store.fetch(key) do
          set(key, yield) if block_given?
        end
      end

      # Empty the cache
      # @return [Hash] the empty store
      def flush
        mutex.synchronize { @store = {} }
      end

      private

      # Cache a value and return it
      def set(key, value)
        mutex.synchronize do
          store[key] = value
          store.delete(@store.keys.first) if store.length > @length
          value
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rack-component-0.5.0 lib/rack/component/memory_cache.rb
rack-component-0.4.2 lib/rack/component/memory_cache.rb
rack-component-0.4.1 lib/rack/component/memory_cache.rb
rack-component-0.4.0 lib/rack/component/memory_cache.rb