Class: Ambo::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/ambo/store.rb

Overview

This class persists serialized State instance

Constant Summary collapse

REDIS_URL =
ENV.fetch('REDIS_URL') { 'redis://localhost:6379/10' }

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeStore


8
9
10
11
12
# File 'lib/ambo/store.rb', line 8

def initialize
  @redis_pool = ConnectionPool.new(size: 5, timeout: 5) do
    Redis.new(url: REDIS_URL)
  end
end

Class Method Details

.redis_key_for(ctx) ⇒ Object

rubocop:enable Security/MarshalLoad


34
35
36
# File 'lib/ambo/store.rb', line 34

def self.redis_key_for(ctx)
  "ambo:#{ctx.bot_name}"
end

Instance Method Details

#load_or_create(ctx) ⇒ Object

TODO: verify payload before Marshal.load rubocop:disable Security/MarshalLoad


23
24
25
26
27
28
29
30
31
# File 'lib/ambo/store.rb', line 23

def load_or_create(ctx)
  serialized = @redis_pool.with do |conn|
    conn.get(self.class.redis_key_for(ctx))
  end

  (serialized.nil? ? State.new : Marshal.load(serialized)).tap do |state|
    state.update(ctx)
  end
end

#save(ctx, state) ⇒ Object

TODO: sign serialized state before writing it to redis


15
16
17
18
19
# File 'lib/ambo/store.rb', line 15

def save(ctx, state)
  @redis_pool.with do |conn|
    conn.set self.class.redis_key_for(ctx), Marshal.dump(state)
  end
end