Sha256: a9c7c9c9afa257cd4fa82c99b4da855538846ce6c2db1a3a020130e9e40816df

Contents?: true

Size: 1.37 KB

Versions: 2

Compression:

Stored size: 1.37 KB

Contents

module Verdict
  module Storage
    class RedisStorage < BaseStorage
      PAGE_SIZE = 50

      attr_accessor :redis, :key_prefix

      def initialize(redis = nil, options = {})
        @redis = redis
        @key_prefix = options[:key_prefix] || 'experiments/'
      end

      def get(scope, key)
        redis.hget(scope_key(scope), key)
      rescue ::Redis::BaseError => e
        raise Verdict::StorageError, "Redis error: #{e.message}"
      end

      def set(scope, key, value)
        redis.hset(scope_key(scope), key, value)
      rescue ::Redis::BaseError => e
        raise Verdict::StorageError, "Redis error: #{e.message}"
      end

      def remove(scope, key)
        redis.hdel(scope_key(scope), key)
      rescue ::Redis::BaseError => e
        raise Verdict::StorageError, "Redis error: #{e.message}"
      end

      def cleanup(scope)
        clear(scope)
        redis.del(scope_key(scope))
      rescue ::Redis::BaseError => e
        raise Verdict::StorageError, "Redis error: #{e.message}"
      end

      private

      def scope_key(scope)
        "#{@key_prefix}#{scope}"
      end

      def clear(scope, cursor: 0)
        cursor, results = redis.hscan(scope_key(scope), cursor, count: PAGE_SIZE)
        results.map(&:first).each do |key|
          remove(scope, key)
        end
        clear(scope, cursor: cursor) unless cursor.to_i.zero?
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
verdict-0.11.0 lib/verdict/storage/redis_storage.rb
verdict-0.10.0 lib/verdict/storage/redis_storage.rb