Sha256: 85d940feca3a7a5b0e661c157eafc9499bbd13442ef67701fca2a045e4a1f754

Contents?: true

Size: 1.98 KB

Versions: 4

Compression:

Stored size: 1.98 KB

Contents

module Verdict
  module Storage
    class RedisStorage
      attr_accessor :redis, :key_prefix

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

      def retrieve_assignment(experiment, subject_identifier)
        if value = redis.hget(generate_experiment_key(experiment), subject_identifier)
          hash = JSON.parse(value)
          experiment.subject_assignment(
            subject_identifier,
            experiment.group(hash['group']),
            DateTime.parse(hash['created_at']).to_time
          )
        end
      rescue ::Redis::BaseError => e
        raise Verdict::StorageError, "Redis error: #{e.message}"
      end

      def store_assignment(assignment)
        hash = { group: assignment.handle, created_at: assignment.created_at }
        redis.hset(generate_experiment_key(assignment.experiment), assignment.subject_identifier, JSON.dump(hash))
      rescue ::Redis::BaseError => e
        raise Verdict::StorageError, "Redis error: #{e.message}"
      end

      def remove_assignment(experiment, subject_identifier)
        redis.hdel(generate_experiment_key(experiment), subject_identifier)
      end

      def clear_experiment(experiment)
        redis.del(generate_experiment_key(experiment))
        redis.del(generate_experiment_start_timestamp_key(experiment))
      end

      def retrieve_start_timestamp(experiment)
        if started_at = redis.get(generate_experiment_start_timestamp_key(experiment))
          DateTime.parse(started_at).to_time
        end
      end

      def store_start_timestamp(experiment, timestamp)
        redis.setnx(generate_experiment_start_timestamp_key(experiment), timestamp.to_s)
      end


      private

      def generate_experiment_key(experiment)
        "#{@key_prefix}#{experiment.handle}"
      end

      def generate_experiment_start_timestamp_key(experiment)
        "#{@key_prefix}#{experiment.handle}/started_at"
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
verdict-0.3.2 lib/verdict/storage/redis_storage.rb
verdict-0.3.1 lib/verdict/storage/redis_storage.rb
verdict-0.3.0 lib/verdict/storage/redis_storage.rb
verdict-0.2.1 lib/verdict/storage/redis_storage.rb