Sha256: a717a73f61422178bc7cdf17f880dad69793a766354aa9a1896308694dcef756

Contents?: true

Size: 1.23 KB

Versions: 24

Compression:

Stored size: 1.23 KB

Contents

require 'active_support/cache'
require 'lz4-ruby'

module Wovnrb
  class MemoryCache < CacheBase
    @@default_memory_cache_config = {
      cache_megabytes: 200,
      ttl_seconds: 300
    }

    def initialize(config)
      @config = merge_setting(@@default_memory_cache_config, config)
      cache_size = @config[:cache_megabytes].to_f
      ttl = @config[:ttl_seconds].to_i
      @cache_store = ActiveSupport::Cache::MemoryStore.new(expires_in: ttl.seconds, size: cache_size.megabytes)
    end

    def put(key, value)
      @cache_store.write(key, compress(value))
    end

    def get(key)
      stored_value =@cache_store.fetch(key)
      decompress(stored_value) if stored_value
    end

    def options
      @cache_store.options.clone
    end

    private
    def merge_setting(original_config, merging_config)
      config = original_config.clone
      config.keys.each do |key|
        key_string = key.to_s
        if merging_config.has_key?(key_string) && merging_config[key_string].present?
          config[key] = merging_config[key_string]
        end
      end
      config
    end

    def compress(value)
      LZ4::compress(value)
    end

    def decompress(value)
      LZ4::decompress(value, value.bytesize, 'UTF-8')
    end
  end
end

Version data entries

24 entries across 24 versions & 1 rubygems

Version Path
wovnrb-1.1.0 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-1.0.13 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-1.0.12 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-1.0.11 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-1.0.10 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-1.0.9 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-1.0.8 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-1.0.7 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-1.0.6 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-1.0.5 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-1.0.4 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-1.0.2 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-1.0.1 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-1.0.0 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.30 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.29 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.28 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.27 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.26 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.25 lib/wovnrb/text_caches/memory_cache.rb