Class: Laboratory::Adapters::RedisAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/laboratory/adapters/redis_adapter.rb

Overview

rubocop:disable Metrics/ClassLength

Constant Summary collapse

ALL_EXPERIMENTS_KEYS_KEY =
'LABORATORY_ALL_EXPERIMENT_KEYS'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url:) ⇒ RedisAdapter

Returns a new instance of RedisAdapter.



8
9
10
# File 'lib/laboratory/adapters/redis_adapter.rb', line 8

def initialize(url:)
  @redis = Redis.new(url: url)
end

Instance Attribute Details

#redisObject (readonly)

Returns the value of attribute redis.



4
5
6
# File 'lib/laboratory/adapters/redis_adapter.rb', line 4

def redis
  @redis
end

Instance Method Details

#delete(experiment_id) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/laboratory/adapters/redis_adapter.rb', line 43

def delete(experiment_id)
  key = redis_key(experiment_id: experiment_id)
  redis.del(key)

  # Remove from ALL_EXPERIMENTS_KEY_KEY
  experiment_ids = fetch_all_experiment_ids
  experiment_ids.delete(experiment_id)
  redis.set(ALL_EXPERIMENTS_KEYS_KEY, experiment_ids.to_json)
end

#delete_allObject



53
54
55
56
# File 'lib/laboratory/adapters/redis_adapter.rb', line 53

def delete_all
  experiment_ids = fetch_all_experiment_ids
  experiment_ids.each { |experiment_id| delete(experiment_id) }
end

#read(experiment_id) ⇒ Object



27
28
29
30
31
32
33
34
# File 'lib/laboratory/adapters/redis_adapter.rb', line 27

def read(experiment_id)
  key = redis_key(experiment_id: experiment_id)
  response = redis.get(key)

  return nil if response.nil?

  parse_json_to_experiment(JSON.parse(response))
end

#read_allObject



36
37
38
39
40
41
# File 'lib/laboratory/adapters/redis_adapter.rb', line 36

def read_all
  experiment_ids = fetch_all_experiment_ids
  experiment_ids.map do |experiment_id|
    read(experiment_id)
  end
end

#write(experiment) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/laboratory/adapters/redis_adapter.rb', line 12

def write(experiment)
  key = redis_key(experiment_id: experiment.id)
  json = experiment_to_json(experiment)
  redis.set(key, json)

  # Write to ALL_EXPERIMENTS_KEYS_KEY if it isn't already there.
  experiment_ids = fetch_all_experiment_ids

  unless experiment_ids.include?(experiment.id)
    experiment_ids << experiment.id
  end

  redis.set(ALL_EXPERIMENTS_KEYS_KEY, experiment_ids.to_json)
end