Sha256: 1e1fa1c733e6e0cbe8e312a18fbd4aea1b14823dce440bdd491292cdfe2873e3

Contents?: true

Size: 1009 Bytes

Versions: 3

Compression:

Stored size: 1009 Bytes

Contents

module Rack
  class Component
    # Threadsafe in-memory cache
    class ComponentCache
      attr_reader :store

      # Initialize a mutex for threadsafe reads and writes
      LOCK = Mutex.new

      # Store cache in a hash
      def initialize(limit = 100)
        @store = {}
        @limit = limit
      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
          write(key, yield) if block_given?
        end
      end

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

      private

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

    private_constant :ComponentCache
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rack-component-0.3.0 lib/rack/component/component_cache.rb
rack-component-0.2.0 lib/rack/component/component_cache.rb
rack-component-0.1.0 lib/rack/component/component_cache.rb