class ViewComponentReflex::StateAdapter::Redis

Attributes

client[R]
ttl[R]

Public Class Methods

new(redis_opts:, ttl: 3600) click to toggle source
# File lib/view_component_reflex/state_adapter/redis.rb, line 16
def initialize(redis_opts:, ttl: 3600)
  @client = ::Redis.new(redis_opts)
  @ttl = ttl
end

Public Instance Methods

set_state(request, _, key, new_state) click to toggle source
# File lib/view_component_reflex/state_adapter/redis.rb, line 32
def set_state(request, _, key, new_state)
  cache_key = get_key(request, key)
  save_to_redis(cache_key, new_state)
end
state(request, key) click to toggle source
# File lib/view_component_reflex/state_adapter/redis.rb, line 21
def state(request, key)
  cache_key = get_key(request, key)
  value = client.hgetall(cache_key)

  return {} if value.nil?

  value.map do |k, v|
    [k, Marshal.load(v)]
  end.to_h
end
store_state(request, key, new_state = {}) click to toggle source
# File lib/view_component_reflex/state_adapter/redis.rb, line 37
def store_state(request, key, new_state = {})
  cache_key = get_key(request, key)
  optimized_store_to_redis(cache_key, new_state, request)
end
wrap_write_async() { || ... } click to toggle source
# File lib/view_component_reflex/state_adapter/redis.rb, line 42
def wrap_write_async
  client.pipelined do
    yield
  end
end

Private Instance Methods

get_key(request, key) click to toggle source
# File lib/view_component_reflex/state_adapter/redis.rb, line 69
def get_key(request, key)
  id = Redis.extract_id(request)
  "#{id}_#{key}_session_reflex_redis"
end
optimized_store_to_redis(cache_key, new_state, request) click to toggle source

Reduce number of calls coming from store_state to save Redis when it's first rendered

# File lib/view_component_reflex/state_adapter/redis.rb, line 52
def optimized_store_to_redis(cache_key, new_state, request)
  request.env["CACHE_REDIS_REFLEX"] ||= []
  return if request.env["CACHE_REDIS_REFLEX"].include?(cache_key)
  request.env["CACHE_REDIS_REFLEX"].push(cache_key)

  save_to_redis(cache_key, new_state)
end
save_to_redis(cache_key, new_state) click to toggle source
# File lib/view_component_reflex/state_adapter/redis.rb, line 60
def save_to_redis(cache_key, new_state)
  new_state_json = new_state.map do |k, v|
    [k, Marshal.dump(v)]
  end

  client.hmset(cache_key, new_state_json.flatten)
  client.expire(cache_key, ttl)
end