Sha256: 34f61d0c9c2c11e1fa1d9921e96d5636eba920af0ec1d277d061ee61453bf191

Contents?: true

Size: 1.27 KB

Versions: 20

Compression:

Stored size: 1.27 KB

Contents

require 'active_support/cache'
require 'active_support/cache/memory_store'
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

20 entries across 20 versions & 1 rubygems

Version Path
wovnrb-0.2.07.1 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.20 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.19 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.18 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.17 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.16 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.15 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.14 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.13 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.12 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.11 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.10 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.09 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.08 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.07 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.06 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.05 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.04 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.03 lib/wovnrb/text_caches/memory_cache.rb
wovnrb-0.2.02 lib/wovnrb/text_caches/memory_cache.rb