Sha256: ce5fc1e3da622ceb6b2593618adc7e2b19723af149d64fd633627ead4f500391

Contents?: true

Size: 1.09 KB

Versions: 1

Compression:

Stored size: 1.09 KB

Contents

# frozen_string_literal: true

module RediSesh
  class ConnectionWrapper
    POOL_KEYS = %i[pool pool_size pool_timeout].freeze

    def initialize(options = {})
      @options = options
      @store = options[:redis_store]
      @pool = options[:pool]

      raise ArgumentError, 'pool must be an instance of ConnectionPool' if @pool && !@pool.is_a?(ConnectionPool)

      return unless @store && !@store.is_a?(RediSesh::Store)

      raise ArgumentError, "redis_store must be an instance of RediSesh::Store (currently #{@store.class.name})"
    end

    def with(&block)
      if pooled?
        pool.with(&block)
      else
        block.call(store)
      end
    end

    def pooled?
      return @pooled if defined?(@pooled)

      @pooled = POOL_KEYS.any? { |key| @options.key?(key) }
    end

    def pool
      @pool ||= ConnectionPool.new(pool_options) { store } if pooled?
    end

    def store
      @store ||= Store.create(@options[:redis_server])
    end

    def pool_options
      {
        size: @options[:pool_size],
        timeout: @options[:pool_timeout]
      }.compact.to_h
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
redi_sesh-0.1.0 lib/redi_sesh/connection_wrapper.rb