Sha256: 6a18877302e0144e2e9627120bcfb8830cee4e66728f3dfe4b9e67ed9b33b93a

Contents?: true

Size: 964 Bytes

Versions: 3

Compression:

Stored size: 964 Bytes

Contents

module Scrivito

class Cache
  attr_reader :cache_prefix, :fallback_backend

  def initialize(options = {})
    @fallback_backend, @cache_prefix = options[:fallback_backend], options[:cache_prefix]
    @cache = {}
  end

  def read(key)
    value = @cache[key]
    if !value && @fallback_backend
      value = @fallback_backend.read(cache_key_for_fallback_backend(key))
      @cache[key] = value
    end
    value
  end

  def write(key, value, options={})
    @fallback_backend.write(cache_key_for_fallback_backend(key), value, options) if @fallback_backend
    @cache[key] = value
  end

  def fetch(key, &block)
    read(key) || block.call.tap { |value| write(key, value) }
  end

  def clear
    @cache = {}
  end

  private

  def cache_key_for_fallback_backend(key)
    # Workaround for rails/rails#15616. Will be fixed in Rails 4.2.
    key = Digest::SHA1.hexdigest(key)
    @cache_prefix ? "#{@cache_prefix}/#{key}" : key
  end
end

end # module Scrivito

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
scrivito_sdk-0.40.0 lib/scrivito/cache.rb
scrivito_sdk-0.40.0.rc2 lib/scrivito/cache.rb
scrivito_sdk-0.40.0.rc1 lib/scrivito/cache.rb